Java Reference
In-Depth Information
Display 16.13 An Iterator
1
import java.util.HashSet;
2
import java.util.Iterator;
3 public class HashSetIteratorDemo
4{
5
public static void main(String[] args)
6
{
7
HashSet<String> s = new HashSet<String>( );
8
s.add("health");
9
s.add("love");
10
s.add("money");
11
System.out.println("The set contains:");
12
Iterator<String> i = s.iterator( );
13
while (i.hasNext( ))1
14
System.out.println(i.next( ));
15
i.remove( );
16
System.out.println( );
17
System.out.println("The set now contains:");
You cannot “reset” an iterator “to the
beginning.” To do a second iteration,
you create another iterator.
18
i = s.iterator( );
19
while (i.hasNext( ))
20
System.out.println(i.next( ));
21 System.out.println("End of program.");
22 }
23 }
Sample Dialogue
The set contains:
money
love
health
The HashSet<T> object
does not order the elements
it contains, but the iterator
imposes an order on the
elements.
The set now contains:
money
love
End of program.
 
Search WWH ::




Custom Search