I have this program:
import java.util.*; public class test { private String s; public test(String s) { this.s = s; } public static void main(String[] args) { HashSet<Object> hs = new HashSet<Object>(); test ws1 = new test("foo"); test ws2 = new test("foo"); String s1 = new String("foo"); String s2 = new String("foo"); hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2); // removing this line also gives same output. System.out.println(hs.size()); } } Note that this is not a homework. We were asked this question on our quiz earlier today. I know the answers but trying to understand why it is so.
The above program gives 3 as output.
Can anyone please explain why that is?
I think (not sure):
The java.lang.String class overrides the hashCode method from java.lang.Object. So the String objects with value "foo" will be treated as duplicates. The test class does not override the hashCode method and ends up using the java.lang.Object version and this version always returns a different hashcode for every object, so the two test objects being added are treated as different.
Object.hashCodeimplementation uses the address that instance is stored at in memory