Java Reference
In-Depth Information
The program creates a copy of an array list (lines 30, 35, 40). The purpose of this is to keep
the original array list intact and use its copy to perform addAll , retainAll , and removeAll
operations.
Note
All the concrete classes in the Java Collections Framework implement the java.lang.
Cloneable and java.io.Serializable interfaces except that
java.util.PriorityQueue does not implement the Cloneable interface. Thus,
all instances of Cloneable except priority queues can be cloned and all instances of
Cloneable can be serialized.
Cloneable
Serializable
20.1 What is a data structure?
20.2 Describe the Java Collections Framework. List the interfaces, convenience abstract
classes, and concrete classes under the Collection interface.
20.3 Can a collection object be cloned and serialized?
20.4 What method do you use to add all the elements from one collection to another
collection?
Check
Point
20.5
When should a method throw an UnsupportedOperationException ?
20.3 Iterators
Each collection is Iterable . You can obtain its Iterator object to traverse all the
elements in the collection.
Key
Point
Iterator is a classic design pattern for walking through a data structure without having to
expose the details of how data is stored in the data structure.
The Collection interface extends the Iterable interface. The Iterable interface
defines the iterator method, which returns an iterator. The Iterator interface provides a
uniform way for traversing elements in various types of collections. The iterator() method
in the Iterable interface returns an instance of Iterator , as shown in Figure 20.2, which
provides sequential access to the elements in the collection using the next() method. You
can also use the hasNext() method to check whether there are more elements in the iterator,
and the remove() method to remove the last element returned by the iterator.
Listing 20.2 gives an example that uses the iterator to traverse all the elements in an array list.
L ISTING 20.2
TestIterator.java
1 import java.util.*;
2
3 public class TestIterator {
4 public static void main(String[] args) {
5 Collection<String> collection = new ArrayList<>();
6 collection.add( "New York" );
7 collection.add( "Atlanta" );
8 collection.add( "Dallas" );
9 collection.add( "Madison" );
10
11 Iterator<String> iterator = collection.iterator();
12 while (iterator.hasNext()) {
13 System.out.print(iterator.next().toUpperCase() + " " );
14 }
15 System.out.println();
16 }
17 }
create an array list
add elements
iterator
hasNext()
next()
 
 
 
Search WWH ::




Custom Search