Java Collections

Jim's Pages => Java Pages => Collections Framework

The collections framework has been in Java since version 1.2, but Vector and Hashtable were the first things I learned and I still tend to use them by default. Sun now calls them "historical" vestiges. To help get myself into the habit of using the newer classes, I put together this drastic condensation of a JDC Tech Tip on the interfaces and implementations.

Set
Unique elements
List
Ordered access
Map
Key-Value Pairs
HashSet - Unordered ArrayList - Optimized append & get by index HashMap - Good enough for most situations.
TreeSet - Sorted order LinkedList - Optimized insert & delete TreeMap - Keys in sorted order
LinkedHashSet - Insertion order   LinkedHashMap - Keys backed by LinkedList
    IdentityMap - Strict reference equality tests: ==
    WeakHashMap - Keys are weak references to elements. Elements can be GCd if this is the only reference.
  Vector - Historic Hashtable - Historic

It is good practice to declare variables and parameter types with the interfaces and not the concrete classes:

   // Good ...
   List list = new ArrayList();
   Set  set  = new HashSet();
   Map  map  = new TreeMap();

   // Avoid
   ArrayList list = new ArrayList();
   HashSet   set = new HashSet();
   TreeMap   map = new TreeMap();

Here's a tip for sorted maps.  If you only need the sorted version after the map is populated, build a Hashmap and convert it to a TreeMap later:

   // Add and remove elements from unsorted map
   Map map = new HashMap();
   map.put("Foo", "Bar");
   map.put("Bar", "Foo");
   map.remove("Foo");
   map.put("Foo", "Baz");

   // Convert to sorted map before displaying elements
   map = new TreeMap(map);
Revisions  
03/03/2003 New