Chapter 16
Collections, Maps d I
and Iterators
Collections Collections
A J ll i i l h h ld bj d
• A Java collection is any class that holds objects and implements the Collection interface
– For example, the ArrayList<T> o e a p e, t e ay st class is a Java collection class, and c ass s a Ja a co ect o c ass, a d implements all the methods in the Collection interface
– Collections are used along with iterators
• The Collection interface is the highest level of Java's
• The Collection interface is the highest level of Java's framework for collection classes
– All of the collection classes discussed here can be found in package p g java.util
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 16‐2
The Collection Landscape
Wildcards Wildcards
Cl d i f i h ll i f k
• Classes and interfaces in the collection framework can have parameter type specifications that do not fully specify the type plugged in for the type
fully specify the type plugged in for the type parameter
– Because they specify a wide range of argument types they – Because they specify a wide range of argument types, they
are known as wildcards
public void method(String arg1, ArrayList<?> arg2)
– In the above example, the first argument is of type String, while the second argument can be an ArrayList<T> with any base type
ArrayList<T> with any base type
Wildcards Wildcards
A b d b l d ild d if i h
• A bound can be placed on a wildcard specifying that the type used must be an ancestor type or
descendent type of some class or interface descendent type of some class or interface
– The notation <? extends String> specifies that the argument plugged in be an object of any descendent class argument plugged in be an object of any descendent class of String
– The notation <? super String> specifies that the argument plugged in be an object of any ancestor class of String
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 16‐5
The Collection Framework The Collection Framework
Th C ll ti <T> i t f d ib th b i
• The Collection<T> interface describes the basic operations that all collection classes should
implement implement
– The method headings for these operations are shown on the next several slides
f h d b
• Since an interface is a type, any method can be defined with a parameter of type Collection<T>
That parameter can be filled with an argument that is an – That parameter can be filled with an argument that is an
object of any class in the collection framework
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 16‐6
Method Headings in the Collection<T>
Interface ( Part 1 of 10)
Method Headings in the Collection<T>
Interface ( Part 2 of 10)
Method Headings in the Collection<T>
Interface ( Part 3 of 10)
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 16‐9
Method Headings in the Collection<T>
Interface ( Part 4 of 10)
16‐10 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Method Headings in the Collection<T>
Interface ( Part 5 of 10)
Method Headings in the Collection<T>
Interface ( Part 6 of 10)
Method Headings in the Collection<T>
Interface ( Part 7 of 10)
16‐13 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Method Headings in the Collection<T>
Interface ( Part 8 of 10)
16‐14 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Method Headings in the Collection<T>
Interface ( Part 9 of 10)
Method Headings in the Collection<T>
Interface ( Part 10 of 10)
Collection Relationships Collection Relationships
Th b f diff d fi d l h
• There are a number of different predefined classes that implement the Collection<T> interface
– Programmer defined classes can implement it also Programmer defined classes can implement it also
• A method written to manipulate a parameter of type Collection<T> will work for all of these classes, either
i l i i d
singly or intermixed
• There are two main interfaces that extend the
Collection<T> interface: The Set<T> interface and the Collection<T> interface: The Set<T> interface and the List<T> interface
16‐17 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Collection Relationships Collection Relationships
Cl h i l h i f d
• Classes that implement the Set<T> interface do not allow an element in the class to occur more than once
once
– The Set<T> interface has the same method headings as the Collection<T> interface, but in some cases the the Collection<T> interface, but in some cases the semantics (intended meanings) are different
– Methods that are optional in the Collection<T>
interface are required in the Set<T> interface
16‐18 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Collection Relationships Collection Relationships
Cl th t i l t th Li t T i t f h th i
• Classes that implement the List<T> interface have their elements ordered as on a list
– Elements are indexed starting with zero Elements are indexed starting with zero
– A class that implements the List<T> interface allows elements to occur more than once
The List<T> interface has more method headings than the – The List<T> interface has more method headings than the
Collection<T> interface
– Some of the methods inherited from the Collection<T> interface have different semantics in the List<T> interface
have different semantics in the List<T> interface
– The ArrayList<T> class implements the List<T> interface
Methods in the Set<T>
Methods in the Set<T>
• The Set<T> interface has the same method headings as the
i i f b i h i
Collection<T> interface, but in some cases the semantics are different. For example the add methods:
The Set<T> interface is in the java.util package.
The Set<T> interface extends the Collection<T> interface and has all the same method headings given in Display 16.2. However, the semantics of the add methods vary as described g g p y , y below.
public boolean add(T element) (Optional)
If element is not already in the calling object element is added to the calling object and true is If element is not already in the calling object, element is added to the calling object and true is returned. If element is in the calling object, the calling object is unchanged and false is returned.
public boolean addAll(Collection<? extends T> collectionToAdd) (Optional)
Ensures that the calling object contains all the elements in collectionToAdd. Returns true if the calling object changed as a result of the call; returns false otherwise. Thus, if
collectionToAdd is a Set<T> then the calling object is changed to the union of itself
collectionToAdd is a Set<T>, then the calling object is changed to the union of itself
with collectionToAdd.
Methods in the List<T> Interface (P 1 f 16)
(Part 1 of 16)
The List<T> interface has more method headings than the Collection<T> interface.
The List T interface has more method headings than the Collection T interface.
16‐21 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (Part 2 f 16)
2 of 16)
16‐22 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (Part 3 f 16)
3 of 16)
Methods in the List<T> Interface (P 4 f 16)
(Part 4 of 16)
Methods in the List<T> Interface (P 5 f 16)
(Part 5 of 16)
16‐25 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (P 6 f 16)
(Part 6 of 16)
16‐26 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (P 7 f 16)
(Part 7 of 16)
Methods in the List<T> Interface (Part 8 f 16)
8 of 16)
Methods in the List<T> Interface (P 9 f 16)
(Part 9 of 16)
16‐29 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (P 10 f 16)
(Part 10 of 16)
16‐30 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (P 11 f 16)
(Part 11 of 16)
Methods in the List<T> Interface (Part 12 f 16)
12 of 16)
Methods in the List<T> Interface (P 13 f 16)
(Part 13 of 16)
16‐33 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (Part 14 f 16)
14 of 16)
16‐34 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the List<T> Interface (Part 15 f 16)
15 of 16)
Methods in the List<T> Interface (Part 16 f 16)
16 of 16)
Pitfall: Optional Operations Pitfall: Optional Operations
• When an interface lists a method as "optional," it must still be implemented in a class that implements the interface
– The optional part means that it is permitted to write a method that does not completely implement its intended semantics
H if t i i l i l t ti i i th th
– However, if a trivial implementation is given, then the method body should throw an
UnsupportedOperationException UnsupportedOperationException
16‐37 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Tip: Dealing with All Those Exceptions Tip: Dealing with All Those Exceptions
• The tables of methods for the various collection
interfaces and classes indicate that certain exceptions are thrown
– These are unchecked exceptions, so they are useful for debugging, but need not be declared or caught
• In an existing collection class, they can be viewed as run‐ In an existing collection class, they can be viewed as run time error messages
• In a derived class of some other collection class, most or all of them will be inherited
all of them will be inherited
• In a collection class defined from scratch, if it is to
implement a collection interface, then it should throw the
h f d h f
exceptions that are specified in the interface
16‐38 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Concrete Collections Classes Concrete Collections Classes
• The concrete class HashSet<T> implements the Set<T> interface, and can be used if additional methods are not needed
– The HashSet<T> class implements all the methods in the Set<T> interface, and adds only constructors
– The HashSet<T> class is implemented using a hash table p g
• The ArrayList<T> and Vector<T> classes implement the List<T> interface, and can be used if additional methods are not needed
additional methods are not needed
– Both the ArrayList<T> and Vector<T> interfaces implement all the methods in the interface List<T>
– Either class can be used when a Either class can be used when a List<T> List<T> with efficient with efficient random access to elements is needed
Concrete Collections Classes Concrete Collections Classes
Th t l Li k dLi t T i t d i d
• The concrete class LinkedList<T> is a concrete derived class of the abstract class
AbstractSequentialList<T> q
– When efficient sequential movement through a list is needed, the LinkedList<T> class should be used
• The interface SortedSet<T> and the concrete class
• The interface SortedSet<T> and the concrete class TreeSet<T> are designed for implementations of the Set<T> interface that provide for rapid retrieval of elements
– The implementation of the class is similar to a binary tree, but with
ways to do inserting that keep the tree balanced
Methods in the HashSet<T> Class (P 1 f 2)
(Part 1 of 2)
16‐41 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the HashSet<T> Class (P 2 f 2)
(Part 2 of 2)
16‐42 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
HashSet<T> Class Demo (1 of 4) HashSet<T> Class Demo (1 of 4)
1 import java.util.HashSet;
2 import java.util.Iterator;
3 public class HashSetDemo
4 {
5 private static void outputSet(HashSet<String> set)
6 {
7 Iterator<String> i = set.iterator( );
8 while (i.hasNext( ))
9 System.out.print(i.next( ) + " ");
10 System.out.println();
11 }
12 public static void main(String[] args)
13 {
14 HashSet<String> round = new HashSet<String>( );
15 HashSet<String> green = new HashSet<String>( );
16 // Add some data to each set
17 round.add("peas");
18 round.add("ball");
19 round.add("pie");
20 round.add("grapes");
HashSet<T> Class Demo (2 of 4) HashSet<T> Class Demo (2 of 4)
25 System.out.println("Contents of set round: ");
26 outputSet(round);
27 System.out.println("\nContents of set green: ");
28 outputSet(green);
29 System.out.println("\nball in set 'round'? " +
30 round.contains("ball"));
31 System.out.println("ball in set 'green'? " +
32 green.contains("ball"));
33 System.out.println("\nball and peas in same set? " + 34 ((round.contains("ball") &&
35 (round.contains("peas"))) ||
36 (green.contains("ball") &&
37 (green.contains("peas")))));
38 System.out.println("pie and grass in same set? " + 39 ((round.contains("pie") &&
40 (round.contains("grass"))) ||
41 (green.contains("pie") &&
42 (green.contains("grass")))));
HashSet<T> Class Demo (3 of 4) HashSet<T> Class Demo (3 of 4)
43 // To union two sets we use the addAll method.
44 HashSet<String> setUnion = new HashSet<String>(round);
45 round.addAll(green);
46 System.out.println("\nUnion of green and round:");
47 outputSet(setUnion);
48 // To intersect two sets we use the removeAll method.
49 HashSet<String> setInter = new HashSet<String>(round);
50 setInter.removeAll(green);
51 System.out.println("\nIntersection of green and round:
52 outputSet(setInter);
53 System.out.println();
54 }
55 }
16‐45 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
HashSet<T> Class Demo (4 of 4) HashSet<T> Class Demo (4 of 4)
SAMPLE DIALOGUE
Contents of set round:
grapes pie ball peas
Contents of set green:
grass garden hose grapes peas ball in set round? true ball in set round? true ball in set green? false
ball and peas in same set? true pie and grass in same set? false pie and grass in same set? false
Union of green and round:
garden hose grass peas ball pie grapes
Intersection of green and round:
peas grapes
16‐46 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Using HashSet with your own Class Using HashSet with your own Class
• If you intend to use the HashSet<T> class with your own class as the parameterized type T ,
y p yp
then your class must override the following methods:
methods:
– public int hashCode();
Id ll i i f hi bj
• Ideally returns a unique integer for this object
– public boolean equals(Object obj);
• Indicates whether or not the reference object is the same as the parameter obj
Methods in the Classes ArrayList<T> and
Vector<T> (Part 1 of 15)
Methods in the Classes ArrayList<T> and Vector<T> (Part 2 of 15)
16‐49 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 3 of 15)
16‐50 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 4 of 15)
Methods in the Classes ArrayList<T> and
Vector<T> (Part 5 of 15)
Methods in the Classes ArrayList<T> and Vector<T> (Part 6 of 15)
16‐53 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 7 of 15)
16‐54 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 8 of 15)
Methods in the Classes ArrayList<T> and
Vector<T> (Part 9 of 15)
Methods in the Classes ArrayList<T> and Vector<T> (Part 10 of 15)
16‐57 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 11 of 15)
16‐58 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 12 of 15)
Methods in the Classes ArrayList<T> and
Vector<T> (Part 13 of 15)
Methods in the Classes ArrayList<T> and Vector<T> (Part 14 of 15)
16‐61 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the Classes ArrayList<T> and Vector<T> (Part 15 of 15)
16‐62 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Differences Between ArrayList<T> and Vector<T>
• For most purposes, the ArrayList<T> and Vector<T> are equivalent
– The Vector<T> class is older, and had to be retrofitted with extra method names to make it fit into the collection
f k
framework
– The ArrayList<T> class is newer, and was created as part of the Java collection framework
part of the Java collection framework
– The ArrayList<T> class is supposedly more efficient than the Vector<T> class also
than the Vector<T> class also
Pitfall: Omitting the <T>
Pitfall: Omitting the <T>
Wh h di l i
• When the <T> or corresponding class name is omitted from a reference to a collection class, this is an error for which the compiler may or may not issue an error for which the compiler may or may not issue an error message (depending on the details of the code) and even if it does the error message may be code), and even if it does, the error message may be quite strange
– Look for a missing <T> g or <ClassName> when a
program that uses collection classes gets a strange error
message or doesn't run correctly
The Map Framework The Map Framework
Th J f k d l i h ll i f d d
• The Java map framework deals with collections of ordered pairs
– For example, a key and an associated value For example, a key and an associated value
• Objects in the map framework can implement mathematical functions and relations, so can be used to construct database
l classes
• The map framework uses the Map<T> interface, the AbstractMap<T> class and classes derived from the AbstractMap<T> class, and classes derived from the AbstractMap<T> class
16‐65 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
The Map Landscape The Map Landscape
Map<K,V>
Implem ents SortedMap<K,V> AbstractMap<K,V>
ts
Imp
TreeMap<K,V> HashMap<K,V>
lements
Interface
A i l li b t t b
Abstract Class
Concrete Class
A single line between two boxes means the lower class or interface is derived from (extends) the higher one.
K and V are type parameters for the type of the keys and elements stored in the map
16‐66 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Concrete Class the keys and elements stored in the map.
The Map<K V> Interface (1 of 3)
The Map<K,V> Interface (1 of 3) The Map<K V> Interface (2 of 3) The Map<K,V> Interface (2 of 3)
The Map<K V> Interface (3 of 3) The Map<K,V> Interface (3 of 3)
16‐69 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Concrete Map Classes Concrete Map Classes
• Normally you will use an instance of a Concrete Map Class
• Here we discuss the HashMap<K,V> Class
– Internally, the class uses a hash table similar to what was discussed in Chapter 15.
– No guarantee as to the order of elements placed in the map.
– If you require order then you should use the
l h i
TreeMap<K,V> class or the LinkedHashMap<K,V>
class
16‐70 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
HashMap<K V> Class HashMap<K,V> Class
• The initial capacity specifies how many “buckets” exist in the hash table.
This would be analogous to the size of the array of the hash table – This would be analogous to the size of the array of the hash table
covered in Chapter 15.
– A larger initial capacity results in faster performance but uses more memory
• The load factor is a number between 0 and 1.
h bl f h h f h b f
– This variable specifies a percentage such that if the number of elements added to the hash table exceeds the load factor then the capacity of the hash table is automatically increased.
• The default load factor is 0.75 and the default initial capacity is 16
The HashMap<K V> Class (1 of 2)
The HashMap<K,V> Class (1 of 2)
The HashMap<K V> Class (2 of 2) The HashMap<K,V> Class (2 of 2)
All of the Map Interface methods are supported, such as get and put
16‐73 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
HashMap Example (1 of 3)
1 // hi l h l l d fi d i h 7
1 // This class uses the Employee class defined in Chapter 7.
2 import java.util.HashMap;
3 import java.util.Scanner;
4 public class HashMapDemo
5 {
5 {
6 public static void main(String[] args)
7 {
8 // First create a hashmap with an initial size of 10 and
9 // th d f lt l d f t
9 // the default load factor
10 HashMap<String,Employee> employees =
11 new HashMap<String,Employee>(10);
12 // Add l l bj t t th i
12 // Add several employees objects to the map using
13 // their name as the key
14 employees.put("Joe",
15 new Employee("Joe",new Date("September", 15, 1970)));
16 l t("A d "
16 employees.put("Andy",
17 new Employee("Andy",new Date("August", 22, 1971)));
18 employees.put("Greg",
19 new Employee("Greg",new Date("March", 9, 1972)));
20 l t("Kiki"
20 employees.put("Kiki",
21 new Employee("Kiki",new Date("October", 8, 1970)));
22 employees.put("Antoinette",
23 new Employee("Antoinette",new Date("May", 2, 1959)));
24 S t t i t("Add d J A d G Kiki ")
16‐74 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
24 System.out.print("Added Joe, Andy, Greg, Kiki, ");
25 System.out.println("and Antoinette to the map.");
HashMap Example (2 of 3)
26 // Ask the user to type a name. If found in the map,
27 // print it out.
28 Scanner keyboard = new Scanner(System.in); y ( y );
29 String name = "";
30 do
31 {
32 System.out.print("\nEnter a name to look up in the map. "); y p ( p p ) 33 System.out.println("Press enter to quit.");
34 name = keyboard.nextLine();
35 if (employees.containsKey(name))
36 {
37 Employee e = employees.get(name);
38 System.out.println("Name found: " + e.toString());
39 }
40 else if (!name.equals("")) q
41 {
42 System.out.println("Name not found.");
43 }
44 } while (!name.equals(""));
45 }
46 }
HashMap Example (3 of 3)
SAMPLE DIALOGUE
Added Joe, Andy, Greg, Kiki, and Antoinette to the map.
Enter a name to look up in the map. Press enter to quit.
Joe
Name found: Joe September 15, 1970
Enter a name to look up in the map. Press enter to quit.
Andy
Name found: Andy August 22, 1971
Enter a name to look up in the map. Press enter to quit.
Kiki
Name found: Kiki October 8, 1970
Enter a name to look up in the map. Press enter to quit.
Myla
Name not found.
Using HashMap with your own Class
• Just like the HashSet class, If you intend to use the HashMap<K,V> class with your own class p y as the parameterized type K , then your class must override the following methods:
must override the following methods:
– public int hashCode();
Id ll i i f hi bj
• Ideally returns a unique integer for this object
– public boolean equals(Object obj);
• Indicates whether or not the reference object is the same as the parameter obj
16‐77 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Iterators Iterators
• An iterator is an object that is used with a collection to provide sequential access to the collection elements
collection elements
– This access allows examination and possible modification of the elements
• An iterator imposes an ordering on the
elements of a collection even if the collection itself does not impose any order on the
itself does not impose any order on the elements it contains
– If the collection does impose an ordering on its If the collection does impose an ordering on its elements, then the iterator will use the same ordering
16‐78 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
The Iterator<T> Interface The Iterator<T> Interface
J id i f
• Java provides an Iterator<T> interface
– Any object of any class that satisfies the Iterator<T>
interface is an Iterator<T>
interface is an Iterator<T>
• An Iterator<T> does not stand on its own
It must be associated with some collection object using the – It must be associated with some collection object using the
method iterator
– If c is an instance of a collection class (e.g., ( g ,
HashSet<String>), the following obtains an iterator for c:
It t it t F C it t ()
Iterator iteratorForC = c.iterator();
Methods in the Iterator<T> Interface (Part
1 of 2)
Methods in the Iterator<T> Interface (Part 2 of 2)
16‐81 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Using an Iterator with a HashSet<T> Object Using an Iterator with a HashSet<T> Object
• A HashSet<T> object imposes no order on the elements it contains
• However, an iterator will impose an order on the elements in the hash set
– That is, the order in which they are produced by next() – Although the order of the elements so produced may be g p y
duplicated for each program run, there is no requirement that this must be the case
16‐82 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
An Iterator (Part 1 of 3)
An Iterator (Part 1 of 3) An Iterator (Part 2 of 3) An Iterator (Part 2 of 3)
An Iterator (Part 3 of 3) An Iterator (Part 3 of 3)
16‐85 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Tip: For Each Loops as Iterators Tip: For‐Each Loops as Iterators
• Although it is not an iterator, a for‐each loop can serve the same purpose as an iterator p p
– A for‐each loop can be used to cycle through each element in a collection
element in a collection
• For‐each loops can be used with any of the
ll i di d h
collections discussed here
16‐86 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
For Each Loops as Iterators (Part 1 of 2)
For‐Each Loops as Iterators (Part 1 of 2) For Each Loops as Iterators (Part 2 of 2) For‐Each Loops as Iterators (Part 2 of 2)
The ListIterator<T>
Interface
Th Li tIt t <T> i t f t d th
• The ListIterator<T> interface extends the Iterator<T> interface, and is designed to work with collections that satisfy the List<T> interface with collections that satisfy the List<T> interface
– A ListIterator<T> has all the methods that an Iterator<T> has, plus additional methods
A i i i h di i l
– A ListIterator<T> can move in either direction along a list of elements
– A ListIterator<T> has methods, such as set , and add, that can be used to modify elements
16‐89 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the ListIterator<T> Interface (Part 1 of 4)
16‐90 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
Methods in the ListIterator<T> Interface (Part 2 of 4)
Methods in the ListIterator<T> Interface
(Part 3 of 4)
Methods in the ListIterator<T> Interface (Part 4 of 4)
16‐93 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
The ListIterator<T> Cursor The ListIterator<T> Cursor
E Li tIt t T h iti k k
• Every ListIterator<T> has a position marker known as the cursor
– If the list has n elements, they are numbered by indices 0 through n‐1, If the list has n elements, they are numbered by indices 0 through n 1, but there are n+1 cursor positions
– When next() is invoked, the element immediately following the cursor position is returned and the cursor is moved forward one cursor cursor position is returned and the cursor is moved forward one cursor position
– When previous() is invoked, the element immediately before the cursor position is returned and the cursor is moved back one cursor cursor position is returned and the cursor is moved back one cursor position
16‐94 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
ListIterator<T> Cursor Positions
ListIterator<T> Cursor Positions Pitfall: next and previous Can Return a Reference
Th i ll h i i
• Theoretically, when an iterator operation returns an element of the collection, it might return a copy or clone of the element or it might return a reference clone of the element, or it might return a reference to the element
• Iterators for the standard predefined collection
• Iterators for the standard predefined collection classes, such as ArrayList<T> and
HashSet<T> , actually return references HashSet<T> , actually return references
– Therefore, modifying the returned value will modify the
element in the collection
An Iterator Returns a Reference (Part 1 f 4)
of 4)
16‐97 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
An Iterator Returns a Reference (Part 2 f 4)
2 of 4)
16‐98 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.
An Iterator Returns a Reference (Part 3 f 4)
3 of 4)
An Iterator Returns a Reference (Part 4 f 4)
of 4)
Tip: Defining Your Own Iterator Classes Tip: Defining Your Own Iterator Classes
Th i ll li l d f d fi d
• There is usually little need for a programmer defined Iterator<T> or ListIterator<T> class
• The easiest and most common way to define a collection class The easiest and most common way to define a collection class is to make it a derived class of one of the library collection classes
– By doing this, the iterator() and listIterator() methods automatically become available to the program
• If a collection class must be defined in some other way, then If a collection class must be defined in some other way, then an iterator class should be defined as an inner class of the collection class
16‐101 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.