Using the Collection Classes

Contact Us or call 1-877-932-8228
Using the Collection Classes

Using the Collection Classes

The following are several examples of collection classes:

Vector stores objects in a linear list, in order of addition. Some additional notes on Vector are:

  • You can insert and delete objects at any location.
  • All methods are synchronized, so that the class is thread-safe.
  • Vector predates the collections framework, but was marked to implement List when the collections API was developed
    • As a result, there are many duplicate methods, like add and addElement, since the names chosen for Collection methods didn't all match existing method names in Vector.
  • Vector was used extensively in the past, and therefore you will see it in a lot of code, but most recent code uses ArrayList instead.

ArrayList, like Vector, stores objects in a linear list, in order of addition. Methods are not synchronized, so that the class is not inherently thread-safe (but there are now tools in the Collections API to provide a thread-safe wrapper for any collection, which is why Vector has fallen into disuse).

TreeSet stores objects in a linear sequence, sorted by a comparison, with no duplicates. TreeSet also:

  • Stores Comparable items or uses a separate Comparator object to determine ordering.
  • Uses a balanced tree approach to manage the ordering and retrieval.

Note that there is no tree list collection, because the concepts of insertion order and natural order are incompatible. Since sets reject duplicates, any comparison algorithm should include a guaranteed tiebreaker (for example, to store employees in last name, first name order: to allow for two Joe Smiths, we should include the employee id as the final level of comparison).

TreeMap stores objects in a Map, where any subcollection or iterator obtained will be sorted by the key values. Note that:

  • Keys must be Comparable items or have a separate Comparator object.
  • For maps, an iterator is not directly available. You must get either the key set or entry set, from which an iterator is available.

Hashtable stores objects in a Map. Note also that:

  • All methods are synchronized, so that the class is thread-safe.
  • Hashtable predates the collections framework, but was marked to implement Map when the collections API was developed.
  • Like Vector, Hashtablehas some duplicate methods.
  • Hashtable extends an obsolete class called Dictionary.

HashSet uses hashing strategy to manage a Set. Note also that:

  • HashSet rejects duplicate entries.
  • Entries are managed by an internal HashMap that uses the entry hashCode values as the keys.
  • Methods are not synchronized.
Next