Java Reference
In-Depth Information
C OLLECTIONS B ACKGROUND
Before Java 1.2, the java.util package had two primary classes that implemented
functionality similar to the functionality of the Java Collections framework: Vector
and Hashtable . A Vector may be thought of as an array that can expand or contract
dynamically as objects are added to it or taken from it. A Hashtable may be thought
of as a group of objects, each of which is paired with or indexed by a key.
If you ever work with programs written before Java 1.2, you will probably find
extensive usage of Vectors and Hashtables . Vectors are indispensable in situations
in which you needed to maintain in memory a list of objects but could not predict
the exact number of objects you would have.
Java 1.2 created a much more powerful framework for handling groups of ob-
jects. The Collections framework is an extensible assortment of supporting classes
and interfaces. Vector and Hashtable still exist and operate much the way they used
to in prior versions of Java. Code written with Vector and Hashtable in Java 1.1 or
before will compile and work the same in Java 1.2.
Vector and Hashtable stand out from the rest of the Collections framework be-
cause they are legacy classes. The methods for adding and retrieving objects from
them are different from those for the rest of the framework. They are also different
in another big way: The methods for manipulating the objects in Vector and
Hashtable are synchronized. This means that you can add and remove objects from
them from multiple threads at the same time, and the class maintains its internal
consistency. That sounds good, but it can be costly; synchronized code carries a
heavy performance penalty. If you are writing a single-thread application or are
manipulating the objects in the Vector or Hashtable from a single thread, you don't
need to add that overhead.
To a large extent, the newer ArrayList collection class mimics the functional-
ity of Vector , and HashMap mimics the functionality of Hashtable . These collection
classes do not use synchronized methods, so they perform much better when syn-
chronization isn't required.
One useful way to understand collections is to compare them to traditional
COBOL files. COBOL programs can traverse a file in a particular order, looking for
specific records, and then modify or perhaps delete those records. In order to ex-
amine or modify any particular record, the program must first read it into a record
structure. Standard functions exist to read, update, delete, and reorder (sort) the
file. Further, the file has a determinate number of records, and the program can de-
tect when it has reached the end of the file.
All COBOL programmers know how to process files. Data stored in files is
readily available to a COBOL program. If you need to build a program that
Search WWH ::




Custom Search