Contents    Page-10    Prev    Next    Page+10    Index   

Set API in Java

ArrayList and LinkedList are inefficient, O(n), for searching.

The Set interface is a Collection that does not contain duplicate ( .equals() ) elements. (A set-like object that allows duplicates is sometimes called a bag).

TreeSet maintains a set in sorted order, using the natural order of elements ( .compareTo() ), or a comparator. add, remove, and contains are O(log(n)).

The add method adds a new item; it returns true if the add succeeded, or false if the item was already there. Since a Set is a Collection, it has iterators.


Set<String>
   s = new TreeSet<String>
           ( new CaseInsensitiveCompare() );

s.add( "Hello" );

There are also a HashSet and a LinkedHashSet.