Java Reference
In-Depth Information
If you need a sorted Set , there is in fact a SortedSet interface, of which the most common
implementation is a TreeSet ; see a TreeSet example in Avoiding the Urge to Sort .
Using Iterators or Enumerations for Data-Independent
Access
Problem
You want to write your code so that users don't have to know whether you store it in an ar-
ray, a Vector , an ArrayList , or even a doubly linked list of your own choosing.
Solution
Use the Iterator interface.
Discussion
If you are making collections of data available to other classes, you may not want the other
classes to depend on how you have stored the data so that you can revise your class easily at
a later time. Yet you need to publish a method that gives these classes access to your data. It
is for this very purpose that the Enumeration and Iterator interfaces were included in the
java.util package. These provide a pair of methods that allow you to iterate, or step
through, all the elements of a data structure without knowing or caring how the data is
stored. The newer Iterator interface also allows deletions, though classes that implement
the interface are free either to implement the use of deletions or to throw an Unsuppor-
tedOperationException .
Here is IteratorDemo , the previous ArrayList demo rewritten to use an Iterator to ac-
cess the elements of the data structure:
public
public class
class IteratorDemo
IteratorDemo {
public
public static
static void
void main ( String [] argv ) {
List < Date > l = new
new ArrayList <>();
StructureDemo source = new
new StructureDemo ( 15 );
Search WWH ::




Custom Search