Java Language Initialization


Example

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

Set have its implementation in various classes like HashSet, TreeSet, LinkedHashSet.

For example:

HashSet:

Set<T> set = new HashSet<T>();

Here T can be String, Integer or any other object. HashSet allows for quick lookup of O(1) but does not sort the data added to it and loses the insertion order of items.

TreeSet:

It stores data in a sorted manner sacrificing some speed for basic operations which take O(lg(n)). It does not maintain the insertion order of items.

TreeSet<T> sortedSet = new TreeSet<T>();

LinkedHashSet:

It is a linked list implementation of HashSet Once can iterate over the items in the order they were added. Sorting is not provided for its contents. O(1) basic operations are provided, however there is higher cost than HashSet in maintaining the backing linked list.

LinkedHashSet<T> linkedhashset = new LinkedHashSet<T>();