In Java, the Set is an interface that extends the Collection interface. The set interface provides features of the mathematical Set. The mathematical definition for the Set is "set is a well-defined collection of distinct objects and arrangement of objects n the set doesn't matter". As per the description, the Set interface doesn't allow duplicate values and doesn't maintain insertion order.
The Set is an interface so we cannot provide a direct implementation of it. We can use the following classes to implement the functionalities of Set.
- HashSet
- LinkedHashSet
- EnumSet
- TreeSet
The Set is present in Java.util package we must import Java .util.Set before using it.
Set<Integer> set1= HashSet<>();
Set<Integer> set2= LinkedHashSet<>();
Set with HashSet Implementation:
import java.util.Set;
import java.util.HashSet;
public class HashSetImpl {
public static void main(String[] args) {
//Create Set with HashSet class
Set set = new HashSet();
//Adding elements to set
set.add(1);
set.add(9);
set.add("A");
set.add(4);
set.add(1);
//Printing the values of Set
System.out.println("Set values: "+set);
}
}
output:
Set values: [1, A, 4, 9]
From the above example, you can observe that Set not maintaining the insertion order and removes the duplicates.
Set with TreeSet Implementation:
import java.util.Set;
import java.util.TreeSet;
public class TreeSetImpl {
public static void main(String[] args) {
//Create Set with TreeSet class
Set<String> treeSet = new TreeSet<>();
//Adding elements to set
treeSet.add("D");
treeSet.add("C");
treeSet.add("A");
treeSet.add("B");
treeSet.add("A");
//Printing the values of Set
System.out.println("Set values: "+treeSet);
}
}
output:
Set values: [A, B, C, D]
From the above example, you can observe that TreeSet doesn't maintain insertion order and removes the duplicates. The most important feature of TreeSet keeps the objects in sorted order.
Difference between List & Set:
- The List is an ordered collection of objects it maintains insertion order.
- Set is an unordered collection of object it doesn't maintain insertion order except LinkedHashSet.
- List allows duplicate values.
- The Set doesn't allow duplicate values.
- The List permits multiple null values.
- The Set allows only one null value.
- List implementations ArrayList, LinkedList
- Set implementations HashSet, TreeSet.
0 Comments