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 function adds the element only if the specified element is not already present in the set else the function return 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 element is 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.
Below programs illustrate the use of Java.util.Set.add() method:
Program 1:
// 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 Set<String> s = new HashSet<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); } } |
Set: [Set, 4, Geeks, Welcome, To]
Program 2:
// 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 Set<Integer> s = new HashSet<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); } } |
Set: [50, 20, 40, 10, 60, 30]
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)
Recommended Posts:
- Java.lang.Short toString() method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java lang.Long.builtcount() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java 8 | ArrayDeque removeIf() method in Java with Examples
- Java Clock withZone() method in Java with Examples
- Java Clock tickMinutes() method in Java with Examples
- Map put() Method in Java with Examples
- Set contains() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

