Curriculum
In Java, a HashSet is a class in the Java Collections Framework that is used to implement a set, which is an unordered collection of unique elements. HashSet stores the elements in a hash table which allows for quick access and retrieval of elements.
Here’s an example of how to use HashSet in Java:
import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // create a HashSet HashSet<String> hashSet = new HashSet<String>(); // add elements to the HashSet hashSet.add("element1"); hashSet.add("element2"); hashSet.add("element3"); // print the HashSet System.out.println("HashSet: " + hashSet); // check if an element is in the HashSet boolean containsElement = hashSet.contains("element2"); System.out.println("HashSet contains element2: " + containsElement); // remove an element from the HashSet hashSet.remove("element3"); System.out.println("HashSet after removing element3: " + hashSet); // clear the HashSet hashSet.clear(); System.out.println("HashSet after clearing: " + hashSet); } }
Output:
HashSet: [element3, element2, element1] HashSet contains element2: true HashSet after removing element3: [element2, element1] HashSet after clearing: []
Â
Here are some of the commonly used methods of HashSet:
add(E e)
: Adds the specified element to the set if it is not already present.remove(Object o)
: Removes the specified element from the set if it is present.contains(Object o)
: Returns true if the set contains the specified element.size()
: Returns the number of elements in the set.isEmpty()
: Returns true if the set contains no elements.clear()
: Removes all of the elements from the set.addAll(Collection<? extends E> c)
: Adds all of the elements in the specified collection to the set.removeAll(Collection<?> c)
: Removes all of the elements in the specified collection from the set.retainAll(Collection<?> c)
: Retains only the elements in the set that are contained in the specified collection.iterator()
: Returns an iterator over the elements in the set.toArray()
: Returns an array containing all of the elements in the set.containsAll(Collection<?> c)
: Returns true if the set contains all of the elements in the specified collection.equals(Object o)
: Compares the specified object with the set for equality.hashCode()
: Returns the hash code value for the set.It is important to note that HashSet does not maintain the order of the elements in the set. If you need to maintain the order of the elements, you can use LinkedHashSet instead.