A HashSet
is a class in the Java Collections Framework that implements the Set
interface and stores a collection of unique elements. It uses a hash table to store the elements, which allows for fast lookups and insertions.
Here is an example of how to create a HashSet
in Java:
HashSet<String> set = new HashSet<>();
In this example, the set
variable is a HashSet
object that stores strings. The HashSet
class has a single generic type parameter: the type of the elements (String
in this case).
You can add elements to the HashSet
using the add
method.
For example:
set.add("apple"); set.add("banana"); set.add("orange");
To check if an element is in the HashSet
, you can use the contains
method and specify the element.
For example:
if (set.contains("apple")) { // the element "apple" is in the set }
You can use the size
method of the HashSet
class to get the number of elements in the set.
For example:
int size = set.size(); // returns 3
You can use the isEmpty
method of the HashSet
class to check if the set is empty.
For example:
if (set.isEmpty()) { // the set is empty }
You can use the clear
method of the HashSet
class to remove all the elements from the set.
For example:
set.clear(); // removes all the elements from the set
You can use the iterator
method of the HashSet
class to get an iterator over the elements in the set.