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 HashSet.
If an index is provided then the new item will be placed at the specified index, pushing all of the following elements in the HashSet ahead by one.
If an index is not provided then the new item will be placed at the end of the HashSet.
Syntax
One of the following:
public boolean add(T item)
public void add(int index, T item)
T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| index | Optional. The position in the HashSet at which to add the item. |
| item | Required. The item to be added to the HashSet. |
Technical Details
| Returns: | Nothing if an index is specified. When an index is not specified it returns true if the HashSet changed and false if the list did not change. |
|---|---|
| Throws: | IndexOutOfBoundsException - If the index is less than zero or greater than the size of the HashSet. |
More Examples
Example
Add an item at a specified position in the 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");
cars.add(2, "Toyota");
System.out.println(cars);
}
}
Related Pages
❮ HashSet Methods