Java HashSet is a class in the Java Collections Framework and it is found in the java.util package that implements the Set interface, and is used to store a collection of unique elements in no particular order.
Creating a HashSet
To create a new instance of a HashSet, you can use the following syntax:
HashSet<datatype> hashSet = new HashSet<datatype>();
Here, datatype
is the type of element that you want to store in the HashSet. For example, if you want to store a collection of strings, you would use:
HashSet<String> stringSet = new HashSet<String>();
Adding Elements to a HashSet
To add elements to a HashSet, you can use the add()
method:
hashSet.add(element);
Here, element
is the element that you want to add to the HashSet. Note that if you try to add an element that already exists in the HashSet, it will not be added again, since HashSet only stores unique elements.
Removing Elements from a HashSet
To remove elements from a HashSet, you can use the remove()
method:
hashSet.remove(element);
Here, element
is the element that you want to remove from the HashSet. Note that if the element does not exist in the HashSet, nothing will happen.
Checking if an Element Exists in a HashSet
To check if an element exists in a HashSet, you can use the contains()
method:
hashSet.contains(element);
Here, element
is the element that you want to check for existence in the HashSet. The method returns true
if the element exists in the HashSet, and false
otherwise.
Iterating over a HashSet
To iterate over the elements in a HashSet, you can use a for-each loop:
for (datatype element : hashSet) { // Do something with element }
Here, datatype
is the type of element that you are storing in the HashSet. Note that the elements will be returned in no particular order.
HashSet Characteristics
Some important characteristics of HashSet are:
- HashSet stores only unique elements.
- HashSet does not maintain the insertion order of the elements.
- HashSet allows
null
elements to be stored. - HashSet provides constant time performance for the basic operations (
add()
,remove()
,contains()
) as long as the hash function evenly distributes the elements in the set. However, in the worst case, these operations may take linear time (O(n)
), wheren
is the number of elements in the set. - HashSet is not synchronized, which means that if multiple threads access a HashSet concurrently and at least one of them modifies the set, it must be synchronized externally.
In conclusion, HashSet is a useful class in Java Collections Framework that provides an efficient way to store a collection of unique elements in no particular order.