Java Reference
In-Depth Information
Chapter 12
Collections
In this chapter, you will learn
What collections are in Java
What the Collections Framework is and its architecture
Different ways for traversing a collection
List , Set , Queue , Map , etc.
Different types of collections such as
Applying algorithms to collections
Obtaining different views of a collection
Creating empty and singleton collections
How hash-based collections work internally
What Is a Collection?
A collection is an object that contains a group of objects. A collection is also known as a container. Each object in a
collection is called an element of the collection.
The concept of collections in Java is no different from the concept of collections in our daily life. You see different
kinds of collections every day. Every collection contains a group of objects. What distinguishes one type of collection
from that of another type? One type of collection is distinguished from another type based on the way they manage
their elements. Let's take a few examples of collections from our daily life.
Let's start with a money jar. A money jar is an example of a collection. It contains a group of coins. Do you put a
coin in the money jar in a specific order? Do you retrieve the coins from the jar in a specific order? Can you put many
coins of the same kind in the jar? Can you remove all coins from the jar in one go or must you take them out one at a
time? Can you call your keyboard a collection? Isn't it a collection of keys? Does a keyboard have duplicate keys?
No, you can't have duplicate keys in a keyboard. However, you can have duplicate coins in your money jar.
Consider a queue of customers at a counter in a post office. Is the queue of customers not a collection of
customers? Definitely, it is. Does this queue follow any specific rule? Yes, it does follow a rule, which is first come, first
served. You can rephrase the rule of first come, first served as First In, First Out ( FIFO ).
Consider a stack of topics at your desk. Is it not also a collection of topics? Yes, it is. Assuming that you deal with
one book at a time, does it follow the rule that the topic that was placed on the stack last will be removed first? All
right, this rule seems to be the opposite of the rule about the collection of customers in a queue at the counter in the
post office. This time, the stack of topics is following the rule of Last In, First Out ( LIFO ).
I just mentioned quite a few examples of collections that follow different rules to manage their elements. What
would you do if you had to model these collections of objects into a Java program? First, you would categorize all
possible kinds of collections that you would deal with in your programs. Then, you would write some reusable generic
 
Search WWH ::




Custom Search