Choosing the right Collection

Here's a guide for selecting the proper implementation of a Set, List, or Map. It was compiled for Java 1.4. Many additions have been made to the Collections Framework since then (notably the Queue and Deque interfaces, and various items in java.util.concurrent). These later additions have been omitted here, since this briefer summary should suffice for most cases.

The best general purpose or 'primary' implementations are likely ArrayList, LinkedHashMap, and LinkedHashSet. Their overall performance is better, and you should use them unless you need a special feature provided by another implementation. That special feature is usually ordering or sorting.

For convenience, "ordering" will here refer to the order of items returned by an Iterator, and "sorting" will here refer to sorting items according to Comparable or Comparator.
 

Interface HasDuplicates? Implementations Historical
Set no HashSet ... LinkedHashSet ... TreeSet
...
List yes ... ArrayList ... LinkedList
...
Vector, Stack
Map no duplicate keys  HashMap ... LinkedHashMap ... TreeMap Hashtable, Properties

Principal features of non-primary implementations:

Iteration order for above implementations: For LinkedHashSet and LinkedHashMap, the re-insertion of an item does not affect insertion order.

For LinkedHashMap, 'access order' is from the least recent access to the most recent access. In this context, only calls to get, put, and putAll constitute an access, and only calls to these methods affect access order.

While being used in a Map or Set, these items must not change state (hence, it's recommended that these items be immutable objects):

Sorting requires either that: To retain the order of a ResultSet as specified in an ORDER BY clause, insert the records into a List or a LinkedHashMap.

See Also :
Use standard Collections
Implementing compareTo
Immutable objects
Prefer Collections over older classes
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -