Sets

A set is a collection of objects that contains no duplicates. Duplicate objects are those that return true when tested with the equals() method.

There are a number of different implementations of the Set interface that have specialized uses, but the most commonly used Set implementation is HashSet. Commonly used methods are add(), remove(), contains(), size() and iterator():

set = new HashSet();
set.add("a");
set.add("a");
set.add("b");

print(set.size());          // prints 2

if (set.contains("a"))
   print("contains a");

for (String s : set)        // order of value unpredictable
   print(s);

list = new ArrayList(set);  // load the set values in to an ArrayList
Collections.sort(list);     // sort the list

for (String s : list)       // returned in sorted order
   print(s);

The HashSet class stores and looks up values in an efficient manner, but the iterator method returns the stored values in an unpredictable order. The TreeSet iterator returns values in the natural order for the data type, and the LinkedHashSet returns values in the order in which they were added.