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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With