Delicious

Which Java collection to use?

Introduction

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.

Java Collection Interfaces

The main type of collections are:

  1. Sets
  2. Lists
  3. Queues
  4. Maps

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:

  1. Ordering - Some sort of ordering in the elements. For example, sorted order, insertion order or no specific ordering.
  2. Duplicates - May or may not want to allow duplicate elements in a collection.
  3. Thread Safe - Ensure the safety of the elements in a collections in case there are multiple threads accessing it.
  4. Key-Value pair - Store in key-value pairs.
  5. Blocking operations - Wait for the collection to become non-empty when retrieving an element.
  6. Random Access - Instant retrieval of an element.
  7. 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.

Click here to download the matrix shown below.


 


Delicious