ArrayList and Iterator

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

EKT472: Object Oriented

Programming
ArrayLists and arrays
 A ArrayList is like an array of Objects
 Differences between arrays and ArrayLists:
 Arrays have special convenience syntax; ArrayLists don’t
 An array is a fixed size, but a ArrayList expands as you add things to it
 This means you don’t need to know the size beforehand

 Arrays can hold primitives or objects, but ArrayLists can only hold objects
 However, autoboxing can make it appear that an ArrayList can hold primitives

2
Generics
 In Java versions 1.4 and earlier, an ArrayList just held Objects, which
could be of any (non-primitive) type
 For compatibility reasons you can still do this, but you will get a lot of
warning messages
 In Java 5 you should specify the class of objects that the ArrayList will hold
 This is done with the new generics syntax

3
Creating a ArrayList the old way

 The syntax for creating ArrayLists has changed between Java 1.4 and Java
5
 For compatibility reasons, the old way still works, but will give you warning
messages
 Here are the (old) constructors:
 import java.util.ArrayList;
 ArrayList vec1 = new ArrayList();
 Constructs an ArrayList with an initial capacity of 10

 ArrayList vec2 = new ArrayList(initialCapacity);

4
Using an ArrayList the old way

 boolean add(Object obj)


 Appends the object obj to the end of this ArrayList
 Example: myArrayList.add("A string is an object");

 Object get(int index)


 Returns the component at position index
 Note that this is returned as an Object; to use it as a String, you must cast it
 Example: String s = (String)myArrayList.get(5);

5
Creating a ArrayList the new way

 Specify, in angle brackets after the name, the type of object that the class
will hold
 Examples:
 ArrayList<String> vec1 = new ArrayList<String>();
 ArrayList<String> vec2 = new ArrayList<String>(10);

 To get the old behavior, but without the warning messages, use the <?>
wildcard
 Example: ArrayList<?> vec1 = new ArrayList<?>();

6
Adding elements to a ArrayList
 boolean add(Object obj)
 Appends the object obj to the end of this ArrayList
 With generics, the obj must be of the correct type, or you
get a compile-time (syntax) error
 Always returns true
 This is for consistency with other, similar classes

 void add(int index, Object element)


 Inserts the element at position index in this ArrayList
 The index must be greater than or equal to zero and less
than or equal to the number of elements in the ArrayList
 With generics, the obj must be of the correct type, or you
get a compile-time (syntax) error

7
Removing elements

 boolean remove(Object obj)


 Removes the first occurrence of obj from this ArrayList
 Returns true if an element was removed
 Uses equals to test if it has found the correct element

 void remove(int index)

 Removes the element at position index from this ArrayList


 void clear()
 Removes all elements

8
Accessing with and without generics

 Object get(int index)


 Returns the component at position index

 Using get the old way:


 ArrayList myList = new ArrayList();
myList.add("Some string");
String s = (String)myList.get(0);

 Using get the new way:


 ArrayList<String> myList = new ArrayList<String>();
myList.add("Some string");
String s = myList.get(0);

 Notice that casting is no longer necessary when we retrieve an


element from a “genericized” ArrayList

9
Searching a ArrayList

 boolean contains(Object element)


 Tests if element is a component of this ArrayList
 Uses equals to test if it has found the correct element

 int indexOf(Object element)


 Returns the index of the first occurrence of element in this ArrayList
 Uses equals to test if it has found the correct element
 Returns -1 if element was not found in this ArrayList

 int lastIndexOf(Object element)


 Returns the index of the last occurrence of element in this ArrayList
 Uses equals to test if it has found the correct element
 Returns -1 if element was not found in this ArrayList

10
Getting information

 boolean isEmpty()
 Returns true if this ArrayList has no elements

 int size()
 Returns the number of elements currently in this ArrayList

 Object[ ] toArray()
 Returns an array containing all the elements of this ArrayList in the correct order

11
More about equals

 There are many different notions of equality


 Example: two sets are equal if they contain the same elements; order of
elements is irrelevant
 Java defines public boolean equals(Object) in the Object class, but
 equals is defined to be the same as ==
 It’s often a good idea to override equals for your own objects
 If you do this, note that the argument should be a general Object

 The String class (and some others) override equals

12
13 Iterators

 ArrayList is part of the Java Collections Framework


 Collection is an interface that specifies the basic operations every
collection (data structure) should have
 Some Collections don’t have a definite order
 Sets, Maps, Graphs
 How to access all the items in a Collection with no specified order?
14 Iterator Interface

 An iterator object is a “one shot” object


 it is designed to go through all the
elements of a Collection once
 if you want to go through the
elements of a Collection again you
have to get another iterator object
 Iterators are obtained by calling
a method from the Collection
15 Iterator Iterface Methods

 The Iterator interface specifies 3 methods:


boolean hasNext()
//returns true if this iteration has more elements

E next()
//returns the next element in this iteration
//pre: hastNext()

void remove()
/*Removes from the underlying collection the last element returned by the
iterator.
pre: This method can be called only once per call to next. After calling, must
call next again before calling remove again.
*/
16 Clicker Question 1
 Which of the following produces a syntax error?
ArrayList<String> list
= new ArrayList<String>();
Iterator<String> it1 = new Iterator(); // I
Iterator<String> it2 = new Iterator(list); // II
Iterator<String> it3 = list.iterator(); // III
A. I
B. II
C. III
D. I and II
E. II and III
17 Iterator

rails
 Imagine a fence made up of fence posts and rail sections

fenceposts
18 Fence Analogy
 The iterator lives on the fence posts
 The data in the collection are the rails
 Iterator created at the far left post
 As long as a rail exists to the right of the Iterator, hasNext() is true

iterator object
19 Fence Analogy
ArrayList<String> names =
new ArrayList<String>();
names.add(“Jan”);
names.add(“Levi”);
names.add(“Tom”);
names.add(“Jose”);
Iterator<String> it = names.iterator();
int i = 0;

“Jan” “Levi” “Tom” “Jose”


20 Fence Analogy
while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 1, prints out Jan

first call to next moves iterator to


next post and returns “Jan”
“Jan” “Levi” “Tom” “Jose”
21 Fence Analogy

while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 2, prints out Levi

“Jan” “Levi” “Tom” “Jose”


22 Fence Analogy

while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 3, prints out Tom

“Jan” “Levi” “Tom” “Jose”


23 Fence Analogy

while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 4, prints out Jose

“Jan” “Levi” “Tom” “Jose”


24 Fence Analogy

while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// call to hasNext returns false
// while loop stops

“Jan” “Levi” “Tom” “Jose”


25 Typical Iterator Pattern
public void printAll(Collection<String> list) {
Iterator<String> it = list.iterator();
while( it.hasNext() ) {
String temp = it.next();
System.out.println( temp );
}
}
Clicker Question 2
 What is output by the following code?
ArrayList<Integer> list;
list = new ArrayList<Integer>();
list.add(3);
list.add(3);
list.add(5);
Iterator<Integer> it = list.iterator();
System.out.print(it.next() + " ");
System.out.print(it.next() + " ");
System.out.print(it.next());
A. 3 B. 3 5 C. 3 3 5
D. 3 3 E. 3 3 then a runtime error
27 remove method

 AnIterator can be used to remove things from the Collection


 Can only be called once per call to next()
public void removeWordsOfLength(int len) { Iterator<String> it = myList.iterator
while( it.hasNext() ) {
String temp = it.next();
if(temp.length() == len)
it.remove();
}
}
// original list = [“dog”, “cat”, “hat”, “sat”]
// resulting list after removeWordsOfLength(3) ?
28 Clicker Question 3
public void printTarget(ArrayList<String> names,
int len) {
Iterator<String> it = names.iterator();
while( it.hasNext() )
if( it.next().length() == len )
System.out.println( it.next() );
}
Given names = [“Jan”, “Ivan”, “Tom”, “George”] and len = 3 what is
output by the printTarget method?
A. Jan Ivan Tom George
B. Jan Tom
C. Ivan George
D. No output due to syntax error
E. No output due to runtime error

You might also like