Hashset In Java
HashSet in Java
HashSet is a part of the Java Collections Framework and is an implementation of the Set interface. It provides a collection that does not allow duplicate elements and has no specific order for its elements. HashSet is based on a hash table data structure, which makes it efficient for adding, removing, and searching for elements in constant time (O(1)) on average.
Declaration and Initialization
To use a HashSet in Java, you need to import the java.util.HashSet
package. Here's an example of declaring and initializing a HashSet:
import java.util.HashSet;
public class Example {
public static void main(String[] args) {
HashSet<String> countries = new HashSet<>();
// Adding elements to the HashSet
countries.add("India");
countries.add("USA");
countries.add("China");
// No duplicate elements allowed
countries.add("India"); // This won't be added
// Accessing elements
for (String country : countries) {
System.out.println(country);
}
// Removing elements
countries.remove("USA");
// Checking if an element exists
boolean exists = countries.contains("China");
System.out.println("China exists in the set: " + exists);
}
}
Common HashSet Operations
Here are some commonly used operations with HashSets:
add(element)
: Adds an element to the HashSet.remove(element)
: Removes an element from the HashSet.contains(element)
: Checks if the HashSet contains a specific element.size()
: Returns the number of elements in the HashSet.isEmpty()
: Checks if the HashSet is empty.clear()
: Removes all elements from the HashSet.
HashSet is a widely used data structure when the requirement is to maintain a unique set of elements without any order. It is an excellent choice for tasks that involve checking for existence or eliminating duplicates from a collection of elements.