Java Set Interface is the child interface of Collection. It is introduced in the java 1.2 version.
If our requirement is to represent a group of individual objects in a single entity, where insertion order is not preserved and duplicate is also not allowed then we can use set.
Java Set Interface doesn’t contain any new methods and that’s why we have to use only collection Interface methods.
HashSet:
The underlying data structure of HashSet is hashtable. It inherits the AbstractSet class. It implements Serializable and cloneable interfaces but not RandomAccess.
Important Point of HashSet:
- Duplicate objects are not allowed.
- Insertion order is not preserved.
- HashSet class is non-synchronized.
- It is working based on the hashCode of the Objects.
- Heterogeneous objects are allowed.
When our frequent operation is search operation, then HashSet is the Best Choice. HashSet doesn’t allow a duplicate object, if we try to insert duplicate objects then we won’t get any error(Compile-time error or Runtime error) .add()
the method simply returns false.
HashSet Constructors:
HashSet h = new HashSet();
When we are creating an empty HashSet object then by default its initial capacity is 16 and the default fill ratio is 0.75.
HashSet h = new HashSet(intinitialCapacity);
When we are creating an empty HashSet object with a specified initial capacity then fill Ratio:0.75 by default.
HashSet h = new HashSet(intinitialCapacity, float fillRatio);
Using this example, we are creating a HashSet object with a specified initial capacity and with a specified fill ratio.
HashSet h = new HashSet(Collection c);
In the above example, we are creating an equivalent HashSet object for the given collection object.
What is the Load Factor & Fill ratio:
The fill ratio and load factor both are the same, Fill ratio of 0.75 means after filling 75% automatically a new HashSet object will be created. This Factor is Called fill ratio or load factor.
Methods of Java HashSet.
- boolean add(E e) -> Using this method we add the specified element in the set.
- boolean isEmpty() -> This method is used to check the set is empty or not, it returns true if the set contains no elements.
- boolean contains(Object o) -> It is used to return true if the set contains the specified element.
- void clear() -> It is used to remove all of the elements from the set.
- int size() -> This method is used to return the number of elements in the set.
Example:
package com.technicalround; import java.util.*; class HashSetDemo1 { public static void main(String[] args) { HashSet set = new HashSet(); set.add("Red"); set.add("Blue"); set.add("Green"); set.add("Yellow"); set.add(null); set.add(10); System.out.println(set.add("Green")); // return false because of duplicate System.out.println(set); // [Red, null, Blue, Yellow, 10, Green] } }
Output:
false [Red, null, Blue, Yellow, 10, Green]
Example 2:
package com.technicalround; import java.util.*; class HashSetDemo2 { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); set.add("Red"); set.add("Blue"); set.add("Green"); set.add("Yellow"); Iterator<String> itr = set.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }
Output:
Red Blue Yellow Green White
In the above example, we are adding some duplicates in Set, but in out we are not getting any duplicates because Set does not allow duplicates. When the set finds any duplicate then it is simply returned false.
LinkedHashSet:
The Underlying Data Structure of LinkedHashSet is a Combination of LinkedList and Hashtable. It is introduced in the java 1.4 version. It is the Child Class of HashSet and implements the Set interface. In LinkedHashSet Insertion order is preserved. LinkedHashSet class is non-synchronized.
Note: When we want to develop Cache based application, then LinkedHashSet and LinkedHashMap is a good choice. Because in both duplicates are not allowed and insertion order must be preserved.
LinkedHashSet Constructors:
HashSet lh = new LinkedHashSet(int capacity);
This method is used to initialize the capacity of the Linkedhashset to the given integer value capacity.
HashSet lh = new LinkedHashSet(int capacity, float fillRatio);
This method is used to initialize both the capacity and the fill ratio of the hash set from its argument.
Example 1:
package com.technicalround; import java.util.*; class LinkedHashSetDemo1 { public static void main(String[] args) { HashSet set = new LinkedHashSet(); set.add("Red"); set.add("Blue"); set.add("Green"); set.add("Yellow"); set.add(null); set.add(10); System.out.println(set.add("Green")); // return false because of duplicate System.out.println(set); // [Red, Blue, Green, Yellow, null, 10] } }
Output:
false [Red, Blue, Green, Yellow, null, 10]
Example 2:
package com.technicalround; import java.util.*; class LinkedHashSetDemo2 { public static void main(String[] args) { HashSet<String> set = new LinkedHashSet<String>(); set.add("Red"); set.add("Blue"); set.add("Green"); set.add("Yellow"); Iterator<String> itr = set.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }
OutPut:
Red Blue Green Yellow
SortedSet:
When our requirement is to represent a group of individual objects, where all objects will be inserted according to some sorting order and without duplicates then we should go for SortedSet.
The important point of SortedSet:
- It is introduced in Java 1.2 version.
- SortedSet is the Child Interface of Set.
- The Sorting can be Either Default Natural Sorting OR Customized Sorting Order.
- Default Natural Sorting for the string in alphabetical order and for numbers, it is Sorting in ascending order.
Method of SortedSet:
- Object first() -> This method is used to get 1st Element of the SortedSet.
- Object last() -> This method is used to get Last Element of the SortedSet.
- boolean isEmpty() -> This method is used to check if a SortedSet is empty or not.
- int size() -> This method is used to get the size of the set.
- boolean removeAll(collection) -> This method is used to remove all the elements from the collection which are present in the set.
- boolean retainAll(collection) -> It is a method that is used to retain all the elements from the set which are mentioned in the given collection.
- SortedSetheadSet(Object obj) -> This method is used to get SortedSet whose Elements are < Object.
- SortedSettailSet(Object obj) -> This method is used to get SortedSet
- SortedSetsubSet(Object obj1, Object obj2) -> This method is used to get SortedSet whose Elements are >= obj1 and < obj2.
Example 1:
package com.technicalround; import java.util.*; class SortedSetDemo { public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); ts.add("Niraj"); ts.add("Rahul"); ts.add("Amit"); ts.add("Sonu"); System.out.println(ts); } }
Output:
[Amit, Niraj, Rahul, Sonu]
Example 2:
package com.technicalround; import java.util.*; class Demo { public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); ts.add("Niraj"); ts.add("Rahul"); ts.add("Amit"); ts.add("Sonu"); System.out.println("Sorted Set : " + ts); String s = "Sunil"; //Checking s string is exists in the SortedSet or not System.out.println("Contains :" + s + " " + ts.contains(s)); System.out.println("First Value :" + ts.first()); // Print the first element System.out.println("Last Value :" + ts.last()); // Print the last element } }
Output:
Sorted Set : [Amit, Niraj, Rahul, Sonu] Contains :Sunil false First Value :Amit Last Value :Sonu
TreeSet:
TreeSet implements Serializable and Cloneable interfaces but not the RandomAccess interface. Heterogeneous Objects are Not Allowed. When we are trying to insert we will get a runtime exception that is ClassCastException.
An important point of TreeSet:
- It is introduced in Java 1.2 version.
- The Underlying Data Structure of TreeSet is a balanced tree.
- In TreeSet insertion order is not preserved and it is based on some sorting order.
- Duplicate Objects are Not allowed.
- Heterogeneous Objects are Not Allowed.
- TreeSet doesn’t allow null elements.
- TreeSet is Implements Serializable and Cloneable Interfaces but Not RandomAccess Interface.
TreeSet Constructors:
TreeSet t = new TreeSet();
When we are creating an empty TreeSet Object then all elements will be inserted according to the default natural sorting order.
TreeSet t = new TreeSet(Comparator c);
Creates an empty Tree Set object where all elements will be inserted according to the customized sorting order which is described by Comparator Object.
TreeSet t = new TreeSet(Collection c);
In the above example, we are creating an equivalent TreeSet object for the given collection object.
Example1 :
package com.technicalround; import java.util.*; class TreeSetDemo1 { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add("INR"); ts.add("USD"); ts.add("EUR"); ts.add("SGD"); System.out.println(ts); } }
Output:
[EUR, INR, SGD, USD]
Example 2:
package com.technicalround; import java.util.*; class TreeSetDemo2 { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add("INR"); ts.add("USD"); ts.add("EUR"); ts.add("SGD"); ts.add(null);//java.lang.NullPointerException System.out.println(ts); } }
Output:
Exception in thread "main" java.lang.NullPointerException
Example 3:
package com.technicalround; import java.util.*; class TreeSetDemo3{ public static void main(String args[]){ TreeSet<Integer> set=new TreeSet<Integer>(); set.add(85); set.add(30); set.add(95); set.add(10); System.out.println("Highest Value: "+set.pollFirst()); System.out.println("Lowest Value: "+set.pollLast()); } }
Output:
Highest Value: 10 Lowest Value: 95
Java Set Interface is a very important topic for interview
Read More topics related to the collection.
- Comparable and Comparator in Java
- Java List Interface
- Java Vector
- Cursors in Java
- Collection Interface
- Collections in java
Read more topics related to java
- Multithreading in java
- Inter thread communication in java
- synchronization in java
- Exception in java
- Inner class in java
Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.