A HashSet is a collection of items where every item is unique, and it is found in the java.util
package:
Instantiate a HashSet named cars to store strings.
import
|
The HashSet
class has many useful methods. For example, to add items to it, use the add()
method:
// Import the HashSet class
import
public |
Note: In the example above, despite adding “BMW” twice, it only appears once in the set because each item in a set must be unique.
To check whether an item exists in a HashSet, use the contains()
method:
|
Use the remove() method to eliminate an item.
cars.remove(“Volvo”); |
To eliminate all items, employ the clear() method.
|
To determine the number of items present, utilize the size() method.
|
Use a for-each loop to iterate through the elements of a HashSet.
for |
Items in a HashSet are actually objects. In the examples above, we created items (objects) of type “String”. Remember that in Java, a String is an object, not a primitive type. To use other types, such as int, you must use the corresponding wrapper class, which is Integer. For other primitive types, use their respective wrapper classes: Boolean for boolean, Character for char, Double for double, and so on.
Utilize a HashSet to store Integer objects.
import
|