![]() |
VOOZH | about |
The Set interface is present in java.util package. It is basically a collection of objects with no duplicate objects that means there can be no two objects in a Set e1 and e2 such that e1.equals(e2) and at most one null element. It is an interface that models the mathematical set. This interface inherits the features from the Collection interface and places a feature that restricts the addition of duplicate elements on its own. The two interfaces which implement the Set interface are SortedSet and NavigableSet.
👁 Generic Set In JavaIn this image, the NavigableSet inherits/extends the SortedSet. Now, since the Set doesn't retain the original order of insertion of elements, so NavigableSet provides the implementation of this interface to navigate the set. TreeSet which is an implementation of a Red-Black Tree and implements the NavigableSet.
Declaration of a Set Interface
public interface Set extends Collection{
}
Syntax of a Set
Set< Integer > set = new HashSet< Integer >();
Now, this is targeted to only Integer datatype. i.e only Integer instances can be put in the Set. If we try to put something else in the Set, the compiler will give an error. The checks of generic type occur at the time of compilation.
Syntax of a Generic Set
Set< T > set = new HashSet< T >();
Above syntax is a generalized way to use T to show the generic behavior of a Set which means that T can be replaced with any non-primitive like Integer, String, Double, Character, or any user-defined type.
add() method is used to add elements in a Set. If the element already exists in the Set, it returns false
Set<Character> set = new HashSet<Character>(); Character ch = 'a'; set.add(ch);
The difference is, if we try to add something which is not a Character, then the compiler will show an error.
1. We can use an iterator to iterate over a Set.
Set<Integer> set = new HashSet<Integer>();
Iterator<Iterator> it = set.iterator();
while(it.hasNext()){
Integer aInt = iterator.next();
}
2. Another way to iterate over a Set is to use Generic for-loop.
Set<String> set = new HashSet<String>;
for(String st : set) {
System.out.println(st);
}
Example:
Integer Value :100 Integer Value :101 String Value :geeksforgeeks String Value :generics