In this section, we will learn what the HashSet add() method is and how to use it in Java.
What is Java HashSet add() Method?
The Java HashSet add() method is used to add an element to a HashSet object.
Note: if the elements is already in the target HashSet object, then this method doesn’t do anything because such object can’t have a duplicate content.
Java HashSet add() Method Syntax:
public boolean add(E e)
add() Method Parameters:
The method takes one argument and that is the element we want to add to a HashSet object.
add() Method Return Value:
The return value of this method is of type Boolean.
If the argument element was added to the target HashSet object, then the return value will be true. Otherwise, the value false will return instead.
Example: using HashSet add() method
import java.util.HashSet; public class Main { public static void main(String[] args){ HashSet<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); set.add(6); set.add(7); for (int i: set){ System.out.println(i); } } }
Output:
1 2 3 4 5 6 7