Reputation: 1012
I am new to Java so please be gentle!
import java.util.HashSet;
public class HashTest {
private String str;
public HashTest(String str) {
this.str = str;
}
public static void main(String args[]) {
HashTest h1 = new HashTest("1");
HashTest h2 = new HashTest("1");
String s1 = new String("2");
String s2 = new String("2");
HashSet<Object> hs = new HashSet<Object>();
hs.add(h1);
hs.add(h2);
hs.add(s1);
hs.add(s2);
System.out.print(hs.size());
}
}
Output is 3.
My question is -- why 3 ? One of h1
and h2
and one of s1
and s2
should be inserted. Since they are using the same thing to determine equality i.e. String.hashcode
function call.
Upvotes: 3
Views: 508
Reputation: 3456
You have not implemented equals method in your HashTest class. Becoz of that it is treating both h1 & h2 as different objects and inserting in HashSet.
But in case of String, equals is already implemented. So it will override s1 with s2 because both strings are same only.
size of HashSet = one(h1) + one(h2) + one(s2) = 3
Upvotes: 1
Reputation: 10342
Your HashTest object extends Object (all classes extend Object by default), but not String (actually, you cannot extend String because is a final class
, so when the HashSet uses equals to check if an element already exists, is Object.equals()
the one executed, not the String.equals() method.You have to override that method with something like:
public boolean equals(Object o) {
if (o instanceof HashTest) {
return this.str.equals(((HashTest)o).str);
}
return false;
}
Upvotes: 1
Reputation: 3412
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.
Upvotes: 3