Set add() method in Java with Examples
The add() method of Set in Java is used to add a specific element into a Set collection. The set add() function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
Declaration of add() method
boolean add(E element)
Where, E is the type of element maintained
by this Set collection.
Parameters: The parameter element is the type of element maintained by this Set and it refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the set and is new, else it returns False if the element is already present in the set. The below programs illustrate the use of Java.util.Set.add() method:
Examples of add() method in Java
Example 1
Java
import java.io.*;
import java.util.*;
public class TreeSetDemo {
public static void main(String args[])
{
Set<String> s = new HashSet<String>();
s.add( "Welcome" );
s.add( "To" );
s.add( "Geeks" );
s.add( "4" );
s.add( "Geeks" );
s.add( "Set" );
System.out.println( "Set: " + s);
}
}
|
Output
Set: [Set, 4, Geeks, Welcome, To]
Example 2
Java
import java.io.*;
import java.util.*;
public class TreeSetDemo {
public static void main(String args[])
{
Set<Integer> s = new HashSet<Integer>();
s.add( 10 );
s.add( 20 );
s.add( 30 );
s.add( 40 );
s.add( 50 );
s.add( 60 );
System.out.println( "Set: " + s);
}
}
|
Output
Set: [50, 20, 40, 10, 60, 30]
Last Updated :
24 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...