0% completed
The HashSet class in Java provides various operations to manage collections of unique elements. In this lesson, we will cover several fundamental operations on a HashSet, including inserting, removing, checking size, verifying element existence, and converting to an array. Each section includes an explanation, the syntax used for that operation, and a simple example to illustrate its usage.
Inserting elements into a HashSet is done using the add()
method. This method adds an element if it is not already present in the set. Since HashSet only stores unique elements, duplicate insertions are ignored.
boolean add(E e);
Example Explanation:
add("Red")
, add("Green")
, and add("Blue")
calls insert unique color values.Removing elements from a HashSet can be done by specifying the element to remove. The remove()
method deletes the specified element if it exists in the set.
boolean remove(Object o);
Example Explanation:
remove("Green")
call deletes "Green" from the set.HashSet does not support direct updating of elements because it is designed to store unique items. To update an element, you typically remove the old element and add the new one.
Example Explanation:
remove()
.add()
.The size()
method returns the number of elements currently stored in the HashSet. This is useful for determining how many unique items are present.
int size();
Example Explanation:
size()
method counts the unique elements in the set.To check whether a HashSet contains a specific element, use the contains()
method. This method returns true
if the element exists, and false
otherwise.
boolean contains(Object o);
Example Explanation :
contains("Blue")
method checks for the presence of "Blue".The toArray()
method converts the HashSet into an array. This can be useful when you need to process the elements using array-based operations.
Object[] toArray();
Example Explanation:
toArray()
method converts the HashSet into an array of Objects.Arrays.toString()
, showing all elements......
.....
.....