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
139 views
in JAVA by (178k points)
Can a HashSet contain duplicate elements in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

No, a HashSet cannot contain duplicate elements in Java. The HashSet is a collection that implements the Set interface, and it is specifically designed to hold a collection of unique elements. When you try to add an element to a HashSet that is already present in the set, the add() method will simply return false and the HashSet will not be modified.

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, we create a HashSet of strings and add some elements to it. The last element we add, "apple", is already present in the set, so it will not be added again. 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

...