Java Reference
In-Depth Information
Interface
Description
Collection
The root interface in the collections hierarchy from which interfaces Set , Queue
and List are derived.
Set
A collection that does not contain duplicates.
List
An ordered collection that can contain duplicate elements.
Map
A collection that associates keys to values and cannot contain duplicate keys. Map
does not derive from Collection .
Queue
Typically a first-in, first-out collection that models a waiting line ; other orders
can be specified.
Fig. 16.1 | Some collections-framework interfaces.
Object -Based Collections
The collections framework classes and interfaces are members of package java.util . In
early Java versions, the collections framework classes stored and manipulated only Object
references, enabling you to store any object in a collection, because all classes directly or
indirectly derive from class Object . Programs normally need to process specific types of ob-
jects. As a result, the Object references obtained from a collection need to be downcast to
an appropriate type to allow the program to process the objects correctly. As we discussed
in Chapter 10, downcasting generally should be avoided.
Generic Collections
To elminate this problem, the collections framework was enhanced with the generics capa-
bilities that we introduced with generic ArrayList s in Chapter 7 and that we discuss in
more detail in Chapter 20, Generic Classes and Methods. Generics enable you to specify
the exact type that will be stored in a collection and give you the benefits of compile-time
type checking —the compiler issues error messages if you use inappropriate types in your
collections. Once you specify the type stored in a generic collection, any reference you re-
trieve from the collection will have that type. This eliminates the need for explicit type
casts that can throw ClassCastException s if the referenced object is not of the appropriate
type. In addition, the generic collections are backward compatible with Java code that was
written before generics were introduced.
Good Programming Practice 16.1
Avoid reinventing the wheel—rather than building your own data structures, use the in-
terfaces and collections from the Java collections framework, which have been carefully
tested and tuned to meet most application requirements.
Choosing a Collection
The documentation for each collection discusses its memory requirements and its meth-
ods' performance characteristics for operations such as adding and removing elements,
searching for elements, sorting elements and more. Before choosing a collection, review
the online documentation for the collection category you're considering ( Set , List , Map ,
Queue , etc.), then choose the implementation that best meets your application's needs.
Chapter 19, Searching, Sorting and Big O, discusses a means for describing how hard an
 
Search WWH ::




Custom Search