Java Reference
In-Depth Information
Creating Singleton Collections
Sometimes you want to create a collection that needs to have one and only one element in it. This kind of situation
arises when a method accepts a collection as its argument and you have only one object to pass to that method.
Instead of going through the hassle of creating a new collection and adding a lone element to it, you can use one of
the three static methods of the Collections class, which will create an immutable collection with the one specified
element. Those methods are as follows:
<T> Set<T> singleton(T o)
<T> List<T> singletonList(T o)
<K,V> Map<K,V> singletonMap(K key, V value)
Depending on the collection type that you need, you need to pass one or two objects. For a Set and a List , you
need to pass one object, whereas for a Map you need to pass two objects (one for the key and one for the corresponding
value). The following snippet of code creates a singleton set:
Set<String> singletonSet = Collections.singleton("Lonely");
// Throws a runtime exception as a singleton set is immutable
singletonSet.add("Hello");
Understanding Hash-based Collections
You have used many implementation classes for collections that have the word “hash” in their names, such as
HashSet , LinkedHashSet , HashMap , etc. They are known as hash-based collections. They facilitate fast and efficient
storage and retrieval of objects. This section discusses the internal workings of hash-based collections in brief.
Let's start with a daily life example. Assume that you have been given many pieces of paper. Each piece of paper
has a number written on it. Your task is to organize (or store) those pieces of paper so that you can tell us as quickly as
possible whether a specific number exists in the collection of pieces of paper that you were given. You may be given
more pieces of paper with a number on them in the future.
One way to organize all your numbers is to place them all in one bucket, as shown in Figure 12-5 .
1 2 10 99 3
7 8 3 77 45
12 90
Figure 12-5. Placing all numbers in one bucket
When you are asked to verify the existence of number 89, you will have to look at all of the numbers in your bucket,
one at a time, and finally you will say that number 89 does not exist in the collection. In the worst-case scenario, you
will have to search the entire bucket to tell if a specific number exists in the bucket. In the best-case scenario, you
may find the number on the very first attempt. The average time that it takes you to verify the existence of a number
is proportional to the size of the collection. You may realize that organizing your number in one bucket is not very
efficient for retrieval. As the numbers increase, you will take more time to search through them for a specific number.
 
Search WWH ::




Custom Search