Java HashSet add() Method
Example
Add items to a HashSet:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Definition and Usage
The add() method adds an item to the set, if the item is not already in the set.
A set cannot contain duplicates. If the item is already in the set, it is not added again, and the method returns false.
Note: A HashSet has no order, so the items are not printed in the order they were added.
Syntax
public boolean add(T item)
T refers to the data type of items in the set.
Parameter Values
| Parameter | Description |
|---|---|
| item | Required. The item to add to the set. |
Technical Details
| Returns: | true if the item was added, and false if it was already in the set. |
|---|
More Examples
Example
Check if an item was added:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
System.out.println(cars.add("BMW"));
System.out.println(cars.add("Volvo"));
}
}