Java HashSet

</>Coding Tamilan.← Java course & curriculum
Java Masterclass · Lesson 43 / 50 · English

Java HashSet

Keep unique values. Leave order unspecified.

Step-by-step explanationsRunnable JavaPractice + answer

Read this topic in தமிழ் ↗.

By the end of this lesson, you can…

  • Explain the key idea behind HashSet.
  • Read and run a complete example, then predict what changes.
  • Recognize the topic-specific mistake discussed below.
01 / The concept

Understand the idea

A Set models membership without duplicates. HashSet uses equality and hashing to determine membership, and does not guarantee an iteration order. For custom key objects, equals and hashCode must follow a consistent contract.

02 / Step by step

Explore the details

Java HashSet

A HashSet is a collection of elements where every element is unique.

It is part of the java.util package and implements the Set interface.

Create a HashSet

Now you can use methods like add(), contains(), and remove() to manage your collection of unique elements.

Add Elements

To add elements to a HashSet, use the add() method:

Note: In the example above, even though "BMW" is added twice, it only appears once in the set because sets do not allow duplicate elements.

Check If an Element Exists

To check whether an element exists in a HashSet, use the contains() method:

Remove an Element

To remove an element, use the remove() method:

To remove all elements, use the clear() method:

HashSet Size

Use size() to count how many unique elements are in the set:

Note: Duplicate values are not counted – only unique elements are included in the size.

Loop Through a HashSet

Loop through the elements of an HashSet with a for-each loop:

Other Types

Elements in an HashSet are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

The var Keyword

From Java 10, you can use the var keyword to declare a HashSet variable without writing the type twice. The compiler figures out the type from the value you assign.

This makes code shorter, but many developers still use the full type for clarity. Since var is valid Java, you may see it in other code, so it's good to know that it exists:

The Set Interface

Note: Sometimes you will see both Set and HashSet in Java code, like this:

This means the variable (cars) is declared as a Set (the interface), but it stores a HashSet object (the actual set). Since HashSet implements the Set interface, this is possible.

It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.

When Order Matters

Java reference fragmentJAVA
HashSet<String> cars = new HashSet<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");  // duplicate — silently ignored

System.out.println(cars.size());          // 3
System.out.println(cars.contains("BMW")); // true

cars.remove("Ford");
System.out.println(cars);  // [Volvo, BMW] (order not guaranteed)

// Loop through all elements
for (String c : cars) {
    System.out.println(c);
}

In the next chapter, you will learn about TreeSet, which stores unique elements in sorted order.

03 / Read and predict

A complete runnable example

This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.

Main.java · complete runnable exampleJAVA
import java.util.HashSet;
public class Main {
    public static void main(String[] args) throws Exception {
        HashSet<String> topics = new HashSet<>();
        System.out.println(topics.add("Java"));
        System.out.println(topics.add("Java"));
        System.out.println(topics.size());
        System.out.println(topics.contains("Java"));
    }
}
Predict first. Then reveal the expected output / வெளியீடு
true
false
1
true

The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.

04 / Learn by changing

Change it. Run it. Understand it.

Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.

Open Java editor ↗
After the editor loads, choose Load this lesson example, then press RUN.

Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.

05 / Your turn

Make it your own

Practice challenge

Add java with a lowercase j. Does the size change?

Reveal the answer and reasoning / விடை

Yes. Java and java are different String values, so the set now contains two elements.

One mistake to avoid: Do not test HashSet iteration against a fixed order. Use an ordered collection if order is part of the requirement.

Your learning checkpoint

  • Explain the example without reading the output first.
  • Make the change requested in the practice task.
  • Describe why the result changed—or why compilation failed.

Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.

Coding Tamilan · Understand the idea. Try the code. Build the habit.