Which Java collection to use?
Java collections are one of the most commonly used data-structures by all Java professionals. But are you using the right collection class that would best suits your need. Most programmers usually use Vectors, ArrayList, HashMap or the Hashtable. There are many other collection classes available with the JDK that you can use instead of re-inventing logic to suite your needs.
We will be trying to understand the different types of classes and when each Collection class could be used. We wouldn’t be looking into the implementation details of any collection, for that please refer the latest Java Collection API docs.
The Core Collection Framework Interfaces
The core collection frameworks are depicted in the following image.
The main type of collections are:
Maps are not an integral part of the Collection framework, but they are still considered as Collection because of their capability to store and manipulate data as collection of objects.
Sorted Sets and Sorted Maps are basically a sorted version of Sets and Maps.
Factors that could help on deciding a Collection
There are various factors that can be considered when selecting an appropriate collection for a particular problem. These factors are:
- Ordering – Some sort of ordering in the elements. For example, sorted order, insertion order or no specific ordering.
- Duplicates – May or may not want to allow duplicate elements in a collection.
- Thread Safe – Ensure the safety of the elements in a collections in case there are multiple threads accessing it.
- Key-Value pair – Store in key-value pairs.
- Blocking operations – Wait for the collection to become non-empty when retrieving an element.
- Random Access – Instant retrieval of an element.
- Upper Bounds – To limit the maximum number of elements a collection can hold.
There are also other factors like priority, delay etc..
Java Collection Matrix
The following matrix will help in deciding which Java Collection Class would best fit your requirement. Please note that in case of Key-Value based collection I have considered the factors only for the key and ignored the value in this section.Java-Collection-Matrix-Java-Collection-Matrix