HashSet is a class in the Java collections framework that
implements the Set interface. It is a high-performance set implementation that
stores its elements in a hash table, which allows for fast insertion, deletion,
and search operations.
One of the main advantages of using a HashSet is that it
does not allow duplicate elements. When you add an element to a HashSet, it
will first check if the element already exists in the set. If it does, the
element will not be added. If it does not, the element will be added to the
set. This makes HashSet a good choice for storing unique elements.
Here are some common operations you can perform with a
HashSet in Java:
- Adding an element: To add an element to a HashSet, you can use the add() method. For example:
- Removing an element: To remove an element from a HashSet, you can use the remove() method.
- For example:
- set.remove("banana");
- Checking if an element exists: To check if an element exists in a HashSet, you can use the contains() method.
- For example:
- if (set.contains("apple")) {System.out.println("Apple exists in the set.");}
- Iterating over the elements: To iterate over the elements in a HashSet, you can use the for-each loop.
- For example:
- for (String fruit : set) {System.out.println(fruit);}
- Clearing the set: To remove all elements from a HashSet, you can use the clear() method.
- For example:
- set.clear();
In conclusion, HashSet is a useful class in the Java collections framework that allows you to store and manipulate a set of unique elements efficiently. It provides fast insertion, deletion, and search operations and does not allow duplicate elements. By using the various methods provided by the HashSet class, you can perform a variety of operations on a set of elements in your Java program.
Write a java program to perform the following HashSet operations:
i. Iterate through HashSet.ii. Copy Set content to another HashSet.
iii. Delete all elements from HashSet.
iv. Copy all elements from HashSet to an array.
v. Compare two sets and retain elements which are same on both sets.
vi. Eliminate duplicate user defined objects from HashSet.
vii. Find user defined objects from HashSet.
viii. Delete user defined objects from HashSet.