Java Reference
In-Depth Information
interfaces and classes that you could use in a situation where you need to deal with collection of objects. The good
news is that you do not need to write generic code to manage collections. The designers of the Java language realized
the need for it and incorporated a framework in Java libraries, which is called the Collections Framework .
The Collections Framework consists of interfaces, implementation classes, and some utility classes that let you
handle most types of collections that you would encounter in a Java application. If you encounter a collection type for
which Java does not provide an implementation, you can always roll out your own implementation, which will work
seamlessly with the Collections Framework. The Collections Framework is simple, powerful, and an exciting topic to
learn. This chapter will explore the different types of collections available in the Collections Framework. Figure 12-1
shows five types of collections: a bag, a list, a queue, a stack, and a map.
0
1
2
3
4
5
Ken
John
Ken
Adam
Ellen
Donna
John Donna
Adam
Ken
A list
Ellen
Ken
Ken
John
Adam
Ellen
Donna
A bag
A queue
John
(234) 334-9087
John
Donna
Adam
Ellen
Ken
Donna
(341) 234-9087
Adam
(876) 214-8977
Ellen
(675) 129-9810
Ken
(675) 189-7865
A map
A stack
Figure 12-1. A pictorial view of different types of collections
One collection (the map) in the figure stands out: a collection of name-phone pairs. It maps a name to a phone
number. At this point, these pictures are not associated with any specific types of collection classes in Java. They are
just to help you visualize that Java collections are the same as collections in your daily life. Arrows in some collections
indicate the entry and exit of an element to and from the collection. You may observe that some collections enforce
that an element must be added in a certain way to the collection and it must exit (be removed) the collection in a
certain way. For example, in a queue, elements enter from one end and exit from the other end; in a stack, elements
enter and exit from the same end.
Need for a Collection Framework
The support for arrays of primitive and reference types is built into the Java language right from the beginning. Using
an array is also one of the most efficient ways to store and retrieve a group of object references and primitive values.
Why did we need the Collections Framework if we already had arrays in Java?
Using an array in Java has the following advantages:
It can be used to store and retrieve values using indexes, and it is fast.
double
value in an int array, though if the array is of type Object , there is no compile-time type safety
as anything can be stored in the array.
It knows its type. It provides compile-time type checking such as you cannot store a
 
Search WWH ::




Custom Search