Initialization

suggest change

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

Set is implemented by classes such as HashSet, TreeSet, and LinkedHashSet.

For example:

HashSet:

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

Here T can be String, Integer, or any other reference type. HashSet provides average-case O(1) lookup, does not sort its elements, and does not keep insertion order.

TreeSet:

It stores elements in sorted order. Basic operations take O(log n), and it does not keep insertion order. The no-argument constructor requires the elements to be mutually Comparable.

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

LinkedHashSet:

It extends HashSet and keeps a linked list of entries, so iteration follows insertion order. It does not sort its contents. Basic operations are still average-case O(1), with extra cost to maintain the list.

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents