Java Set add() Method
Overview
To add a specific element to a Set collection in Java, utilize the add() method of the Set class. If the supplied element is already existing in the set, the method returns false without adding the element. Otherwise, it adds the element.
Syntax of Java Set add()
The syntax of add() method is as follow
where, E is the type of element maintained by the Set collection.
Parameters of Java Set add()
The parameter element refers to the element that will be added to the Set and is of the kind of element preserved by this Set.
Return Value of Java Set add()
If the element is not already present in the set, the function returns true otherwise, if the element is already present in the set, it returns false.
Exceptions of Java Set add()
- UnsupportedOperationException: If the add operation is not supported by this set.
- ClassCastException: If the class of the specified element prevents it from being added to this set.
- NullPointerException: If the specified element is null and this set does not permit null elements.
- IllegalArgumentException: If some property of the specified element prevents it from being added to this set.
Example
In this code we are going to use the add() method of java to insert elements to HashSet.
Output:
Explanation:
In the above code, we have created a HashSet of Integer and named it s, and added elements to HashSet s by using add() method that will insert elements to HashSet.
What is Java Set add()?
The add() method of Java Collection Interface puts the desired element into this Collection. If it is successful in inserting the element into the designated collection, it returns the Boolean value true else it returns false.
The Java Set add() method takes one parameter which is the value to be inserted in the set.
More Examples
Example 1
In this example we are going to create a HashSet of Integer and will add some Integer to it using the add() method.
Output
Example 2
In this example we are going to create a HashSet of String and add String to it using the add() method.
Output
Code Explanation In the above code, we have created a HashSet of String and added String elements to it by using add().
Example 3
In this example, we are going try adding null to a different HashSet.
Output
Example 4
In this example, the value returned by the Set add() method will be printed.
Output
Conclusion
- To add a specific element to a Set collection in Java, utilize the add() method of the Set class.
- If the supplied element is already existing in the set, the method returns false, otherwise true.
- Exceptions thrown by Set are UnsupportedOperationException , ClassCastException , NullPointerException , and IllegalArgumentException.
- A HashSet can accept null elements.