HashSet, LinkedHashSet And TreeSet in Java
A Set is a collection which does not contain duplicate element. HashSet, LinkedHashSet and TreeSet implements Set interface.
Let's understand all these classes:
1. HashSet:
HashSet actually backed by Hash Table. And the iteration of elements could be different each time.
- HashSet offers constant time performance for basic operations such as add, remove, contains and size.
Note: HashSet is not synchronized and can contain null values.
Syntax:
HashSet<E> set = new HashSet<E>();
OR
Set<E> set = new HashSet<E>();
Some of the useful methods of HashSet described below:
- add(element): adds element in the set
Example:
set.add(12);
set.add(2);
set.add(5);
System.out.println(set); //output: [2, 5, 12] here order of elements could vary
set.add(5); //will not throw any error, but since 5 already exists, it won't add value 5 again in the set
System.out.println(set); //output: [2, 5, 12]
- isEmpty(): returns true if set is empty otherwise returns false
System.out.println(set.isEmpty()); //false, because array contains some elements
- contains(Object o): returns true if the object exists otherwise returns false
System.out.println(set.contains(5)); //true
- remove(Object o): removes object from the list if exists, otherwise throws an error
set.remove(5);
System.out.println(set); //[2, 12]
- size(): returns the number of elements present in the set
System.out.println(set.size()); //returns 3, since array contains 3 elements 12, 2,5
- clear(): removes all the elements from the set
set.clear();
System.out.println(set); //output: [ ]
2. LinkedHashSet:
LinkedHashSet is a combination of LinkedList and HashTable. It preserves the order in which elements are inserted.
Syntax:
Set<E> set = new LinkedHashSet<E>();
OR
LinkedHashSet<E> set = new LinkedHashSet<E>();
LinkedHashSet<E> set = new LinkedHashSet<E>();
Note: It also contains unique values like Set and can contain null values. It is non-synchronized.
The above methods of HashSet will also work for LinkedHashSet.
3. TreeSet:
This class also implements Set interface and uses a tree for storage. Like Set, TreeSet contains only unique elements but in their natural order.(By default in ascending order)
Syntax:
Set<E> set = new TreeSet<E>();
OR
TreeSet<E> set = new TreeSet<E>();
All the methods of HashSet will also work for TreeSet, since they all implements Set interface.
Comments
Post a Comment