Core Java

HashSet In Java

Introduction:

HashSet in Java implements Set interface i.e. it doesn’t allow duplicates. It is internally backed by a HashMap which works on the principle of hashing. 

We can store a null value in a HashSet. Its default capacity is 16 with a load factor of 0.75, where:

Load factor = Number of Stored Elements / capacity

A Java HashSet is non-synchronized. Also, there’s no guarantee to retain the insertion order of elements.

In this tutorial, we’ll learn how to work with a Java HashSet.

Instantiating HashSet:

We can create a Java HashSet using one of the following constructors:

HashSet() // default capacity of 16 with a load factor of 0.75
HashSet(int initialCapacity)
HashSet(int initialCapacity, float loadFactor)
HashSet(Collection c)

Each of these constructor usages is pretty intuitive.

Let’s quickly create a HashSet using the default constructor:

Set<Integer> set = new HashSet<>();

Commonly Used Methods:

Let’s now look at some methods that can help us manipulate over a Java HashSet:

1. boolean add(E e):

It simply adds an element to the given set, if not present already. If the element is already present, add() simply returns false:

System.out.println(set.add(1));  //true
System.out.println(set.add(2));  //true
System.out.println(set.add(3));  //true
System.out.println(set.add(1));  //false - as already present
 
//Note that the order of elements isn't guaranteed
System.out.println(set); //[1, 2, 3]

2. boolean contains(Object obj):

The contains() method returns true if the element exists in the referenced set, false otherwise:

System.out.println(set.contains(1)); //true
System.out.println(set.contains(4)); //false

3. boolean remove(Object obj):

As the name suggests, it removes the element obj if it exists and returns true. If no such element exists, it simply returns false:

System.out.println(set.remove(1)); //true
System.out.println(set.remove(4)); //false

Note that the HashSet also inherits removeAll() and removeIf() methods, which can be used to remove values.

4. boolean isEmpty():

It returns true for an empty set, false otherwise:

System.out.println(set.isEmpty()); // false

5. int size():

It simply returns the number of elements present in the given set.

6. void clear():

The clear() method removes all values present in the referenced set, thereby making it an empty set.

Internal Implementation:

A HashSet internally uses a HashMap to store its elements. The elements stored in a HashSet are mapped as the keys in a HashMap. The value fields of all these entries contain a constant PRESENT:

private static final Object PRESENT = new Object();

which is a dummy object.

Iterating Over HashSet:

We can use one of the following ways to iterate over the elements in a HashSet:

1. forEach():

Java 8 onwards, we can use forEach() to iterate over any Java Collection:

set.forEach(e -> System.out.println(e));

2. forEachRemaining():

Java 8 also supports forEachRemaining() construct to be used with any iterator over a Collection:

Iterator<Integer> itr = set.iterator();
 
itr.forEachRemaining(e -> System.out.println(e));

3. Iterate Using Iterator:

In case we’re on a Java 7 or lower versions, we can simply iterate through using an iterator:

Iterator<Integer> itr = set.iterator();
 
while(itr.hasNext()) {
    System.out.println(itr.next());
}

4. Extended for Loop:

We can also use an extended for loop to traverse through the elements:

for(Integer e : set) {
    System.out.println(e);
}

Conclusion:

In this tutorial, we learned how to create and work with a Java HashSet. We also know that the Java HashSet internally uses a HashMap for its implementation.

Be the First to comment.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: HashSet In Java

Opinions expressed by Java Code Geeks contributors are their own.

Shubhra Srivastava

Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button