Would a Java HashSet<String>'s contains() method test equality of the strings or object identity?

Solution 1:

It uses equals() to compare the data. Below is from the javadoc for Set

adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)).

The equals() method for String does a character by character comparison. From the javadoc for String

The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object

Solution 2:

Actually, HashSet does neither.

Its implementation uses a HashMap, and here's the relevant code that determines if the set contains() (actually it's inside HashMap's getEntry() method):

if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))

which:

  • requires the hashes to equal, and
  • requires either object equality or equals() returns true

The answer is "yes": wordSet.contains(b) will always return true