Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
654 views
in JAVA by (178k points)
How does HashSet ensure uniqueness of elements in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

HashSet in Java ensures uniqueness of elements by using a combination of the hashCode() and equals() methods. When you add an element to a HashSet, the HashSet first calculates the hash code of the element using the element's hashCode() method. It then uses the hash code to determine the index in the internal array where the element should be stored.

If there are no other elements at that index, the element is added to the HashSet and the HashSet ensures that it is unique. However, if there is already an element at that index, the HashSet uses the element's equals() method to compare the new element with the existing element. If the two elements are equal, the new element is not added to the HashSet since it is already present. If the two elements are not equal, the HashSet tries to find another index in the array for the new element.

Here is an example to demonstrate this:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();

        // Adding some elements to the HashSet
        set.add("apple");
        set.add("banana");
        set.add("cherry");
        set.add("apple"); // Duplicate element

        // Printing the HashSet
        System.out.println(set);
    }
}
 

In this example, when we add the element "apple" to the HashSet for the second time, the HashSet will calculate the hash code of the element and use it to determine the index in the internal array. It will then use the equals() method to compare the new "apple" element with the existing "apple" element, and since they are equal, the new element will not be added to the HashSet. When we print the HashSet, the output will be:

[banana, apple, cherry]
 

As you can see, the HashSet contains only three elements and the duplicate element "apple" has been removed.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...