The HashSet
class in Java is part of the java.util
package and implements the Set
interface. It is backed by a hash table (actually a HashMap
instance). HashSet
provides a collection that contains no duplicate elements and offers constant-time performance for basic operations such as add
, remove
, contains
, and size
, assuming the hash function disperses elements properly among the buckets.
HashSet
does not allow duplicate elements. If you try to add a duplicate element, the add
method will simply return false
.HashSet
permits the storage of null
elements.HashSet
are not ordered. The HashSet
does not guarantee that the order will remain constant over time.HashSet
operations are generally faster than TreeSet because they rely on hash codes.Here’s how to create a HashSet
in Java:
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
}
}
To add elements to a HashSet
, you can use the add
method:
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
To remove elements from a HashSet
, you can use the remove
method:
hashSet.remove("Banana");
To check if a HashSet
contains a specific element, use the contains
method:
boolean containsApple = hashSet.contains("Apple"); // returns true
boolean containsBanana = hashSet.contains("Banana"); // returns false
To iterate over the elements in a HashSet
, you can use an iterator, enhanced for loop, or forEach method:
// Using iterator
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using enhanced for loop
for (String fruit : hashSet) {
System.out.println(fruit);
}
// Using forEach method (Java 8 and later)
hashSet.forEach(System.out::println);
Here’s a complete example demonstrating various operations with HashSet
:
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
// Adding elements
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple"); // Duplicate, will not be added
// Checking size
System.out.println("Size of hashSet: " + hashSet.size()); // Output: 3
// Removing an element
hashSet.remove("Banana");
// Checking if an element exists
System.out.println("Contains Apple: " + hashSet.contains("Apple")); // Output: true
System.out.println("Contains Banana: " + hashSet.contains("Banana")); // Output: false
// Iterating over elements
System.out.println("Elements in hashSet:");
for (String fruit : hashSet) {
System.out.println(fruit);
}
// Using forEach method (Java 8 and later)
hashSet.forEach(System.out::println);
}
}
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.iterator()
: Returns an iterator over the elements in the set.TreeSet
: Implements the NavigableSet
interface and uses a tree for storage. The elements in a TreeSet
are ordered. TreeSet
is slower than HashSet
for most operations due to the overhead of maintaining the order.LinkedHashSet
: Extends HashSet
and maintains a linked list of the entries in the set, in the order in which they were inserted. This makes LinkedHashSet
slightly slower than HashSet
but faster than TreeSet
.HashSet
provides constant-time performance for the basic operations (add
, remove
, contains
, and size
) assuming the hash function disperses elements properly among the buckets.HashSet
operations depends on the quality of the hash function. Poorly designed hash functions can lead to many collisions and degrade performance.HashSet
is a powerful and efficient implementation of the Set
interface, suitable for most use cases where a collection with no duplicate elements is needed and order does not matter. Its constant-time performance for basic operations makes it an excellent choice for many scenarios, but it’s important to be aware of the need for a good hash function to maintain optimal performance.