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.