Last Updated : 12 Jul, 2025
The
add()method of
SortedSetin Java is used to add a specific element into a
Setcollection. The 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.
Syntax:boolean add(E element) Where E is the type of element maintained by this Set collection.Parameters:
The parameter
elementis of 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.
Note: This method of
SortedSetis inherited from the
Set interfacein Java. Below programs illustrate the use of Java.util.Set.add() method:
Program 1:
Java
// Java code to illustrate add() method
import java.io.*;
import java.util.*;
public class TreeSetDemo {
public static void main(String args[])
{
// Creating an empty Set
SortedSet<String> s
= new TreeSet<String>();
// Use add() method
// to add elements into the Set
s.add("Welcome");
s.add("To");
s.add("Geeks");
s.add("4");
s.add("Geeks");
s.add("Set");
// Displaying the Set
System.out.println("Set: " + s);
}
}
Output:
Set: [4, Geeks, Set, To, Welcome]Program 2
:
Java
// Java code to illustrate add() method
import java.io.*;
import java.util.*;
public class TreeSetDemo {
public static void main(String args[])
{
// Creating an empty Set
SortedSet<Integer> s
= new TreeSet<Integer>();
// Use add() method
// to add elements into the Set
s.add(10);
s.add(20);
s.add(30);
s.add(40);
s.add(50);
s.add(60);
// Displaying the Set
System.out.println("Set: " + s);
}
}
Output:
Set: [10, 20, 30, 40, 50, 60]Reference
:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4