Because you're checking the equality of the HashTest
objects by comparing their strings in your .equals()
method. Since both of your HashTest
objects have the same string, they are equal. Now, the HashSet object replaces h1
with h2
, I believe.
Edit:
Just realized the output is actually 2
. That's because the second String
added replaces the first as well, since the .eqauls
method of a String
object also compares the actual string and not the reference.
Edit 2:
Regarding your updated code where you get 3
as the output, you have not implemented an equals
method. Therefore, it doesn't compare the actual str
data member of the HashTest
objects. Now it compares references and adds both HashTest
objects since they have different references. So there exists 2 hashtest objects now, and 1 string in your HashSet
now.