Java Reference
In-Depth Information
A set iterator does not visit the elements in the order in which you inserted them.
The set implementation rearranges the elements so that it can locate them quickly.
There is an important difference between the Iterator that you obtain from a set
and the ListIterator that a list yields. The ListIterator has an add method
to add an element at the list iterator position. The Iterator interface has no such
method. It makes no sense to add an element at a particular position in a set, because
the set can order the elements any way it likes. Thus, you always add elements
directly to a set, never to an iterator of the set.
You cannot add an element to a set at an iterator position.
However, you can remove a set element at an iterator position, just as you do with list
iterators.
Also, the Iterator interface has no previous method to go backwards through
the elements. Because the elements are not ordered, it is not meaningful to distinguish
between Ȓgoing forwardȒ and Ȓgoing backwardȓ.
The following test program allows you to add and remove set elements. After each
command, it prints out the current contents of the set. When you run this program, try
adding strings that are already contained in the set and removing strings that aren't
present in the set.
702
703
ch16/set/SetDemo.java
1 import java.util.HashSet;
2 import java.util.Scanner;
3 import java.util.Set;
4 5 /**
6 This program demonstrates a set of strings. The user
7 can add and remove strings.
8 */
9 public class SetDemo
10 {
11 public static void main(String[] args)
Search WWH ::




Custom Search