Java Set is a collection of elements (Or objects) that contains no duplicate elements. Java Set is an interface that extends Collection interface. Unlike List, Java Set is NOT an ordered collection, itâ€™s elements does NOT have a particular order. Java Set doesÂ NOTÂ provide a control over the position where you can insert an element. You cannot access elements by their index and also search elements in the list.
let’s look at the characteristics of each implementation in details:
- HashSet: is the best-performing implementation and is a widely-used Set implementation. It represents the core characteristics of sets: no duplication and unordered.
- LinkedHashSet: This implementation orders its elements based on insertion order. So consider using aÂ LinkedHashSetÂ when you want to store unique elements in order.
- TreeSet: This implementation orders its elements based on their values, either by their natural ordering, or by a Comparator provided at creation time.
Comparison table of SET Implemented classes?
|1||Underlying data Structure||HashTable||Combination of LinkedList and HashTable||Balanced tree|
|2||Duplicate objects||No allowed||Not allowed||Not allowed|
|3||Insertion order||Not Preserved||Preserved||Not Preserved|
|5||Heterogeneous Object||Allowed||Allowed||Not Allowed|
|5||Null Acceptance||Allowed||Allowed||As first element null is allowed(until 1.6 version, 1.7 version onward null is not allowed even as the first element)|