Sobes.tech
Junior — Middle

Is it possible to include a null value in a HashSet?

sobes.tech AI

Answer from AI

Yes, you can add a null value to a HashSet. HashSet in Java allows exactly one null element, as the set does not contain duplicates.

Example:

HashSet<String> set = new HashSet<>();
set.add(null);
set.add("hello");
System.out.println(set.contains(null)); // true

Attempting to add multiple nulls will not cause an error, but only one null will be in the set.

It is important to remember that some other Set implementations (for example, TreeSet) do not allow null, because they use a Comparator for element comparison, which cannot work with null.