Java hashCode doubt -
i have 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 line gives same output. system.out.println(hs.size()); } } note not homework. asked question on our quiz earlier today. know answers trying understand why so.
the above program gives 3 output.
can please explain why is?
i think (not sure):
the java.lang.string class overrides hashcode method java.lang.object. string objects value "foo" treated duplicates. test class not override hashcode method , ends using java.lang.object version , version returns different hashcode every object, 2 test objects being added treated different.
in case it's not hashcode() equals() method. hashset still set, has semantic of not allowing duplicates. duplicates checked using equals() method in case of string return true
however test class equals() method not defined , use default implementation object return true when both references same instance.
method hashcode() used not check if objects should treated same way distribute them in collections based on hash functions. it's absolutely possible 2 objects method return same value while equals() return false.
p.s. hashcode implementation of object doesn't guarantee uniqueness of values. it's easy check using simple loop.
Comments
Post a Comment