Wednesday, March 20, 2013

Selecting your Java Collections library

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:
  • 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 :

There is a nice overview on the whole API with explanation when to use what type of Collections by Janeve George.

References :



Post a Comment