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

OkonX picture OkonX · Jan 23, 2012 · Viewed 57.6k times · Source

Let's say I have this code in Java:

HashSet<String> wordSet = new HashSet<String>();
String a = "hello";
String b = "hello";
wordSet.add(a);

Would wordSet.contains(b); return true or false? From what I understand, a and b refer to different objects even though their values are the same. So contains() should return false. However, when I run this code, it returns true. Will it always return true no matter where String object b is coming from as long as b contains the value "hello"? Am I guaranteed this always? If not, when am I not guaranteed this? And what if I wanted to do something similar with objects other than Strings?

Answer

Aravind Yarram picture Aravind Yarram · Jan 23, 2012

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