In this tutorial, we will learn about the Set interface in Java and its methods.
The Set interface of the Java Collections framework provides the features of the mathematical set in Java. It extends the Collection interface.
The set interface present in the java.util package and extends the Collection interface is an unordered collection of objects in which duplicate values cannot be stored. It is an interface which implements the mathematical set. This interface contains the methods inherited from the Collection interface and adds a feature which restricts the insertion of the duplicate elements. There are two interfaces which extend the set implementation namely SortedSet and NavigableSet.
// Java program to demonstrate a Set
import java.util.*;
public class SetExample{
public static void main(String[] args)
{
// Set demonstration using HashSet
Set<String >hash_Set
= new HashSet <String>();
hash_Set.add("Codemistic");
hash_Set.add("For");
hash_Set.add("Codemistic");
hash_Set.add("Example");
hash_Set.add("Set");
System.out.println(hash_Set);
}
}
output:
[Set, Example, Codemistic, For]
Sr.No. | Method & Description |
---|---|
1 | add( ) Adds an object to the collection. |
2 | clear( ) Removes all objects from the collection. |
3 | contains( ) Returns true if a specified object is an element within the collection. |
4 | isEmpty( ) Returns true if the collection has no elements. |
5 | iterator( ) Returns an Iterator object for the collection, which may be used to retrieve an object. |
6 | remove( ) Removes a specified object from the collection. |
7 | size( ) Returns the number of elements in the collection. |