java - Didnot override hashCode() and equals() methods.But could find my stuff -
according scjp book,if donot override hashcode() , equals() method in class being used part of key our code should run , compile not find out stuff.
did not override hashcode() , equals() method in class used part of key,yet value retrieved.
please find code below:
case 1:
import java.util.hashmap; import java.util.map; class dog1{ public dog1(){} public dog1(string n) { // todo auto-generated constructor stub name=n; } string name; } public class mapgen { public static void main(string[] args) { map<object,object> m = new hashmap<object,object>(); dog1 d1=new dog1("clover"); //dog1 d2 =new dog1("clover"); m.put(d1, "xyz"); system.out.println(""+m.get(d1)); system.out.println(""+m.size()); } }
output:
xyz
1
while in following case see unable retrieve value. case 2:
import java.util.hashmap; import java.util.map; class dog1{ public dog1(){} public dog1(string n) { // todo auto-generated constructor stub name=n; } string name; } public class mapgen { public static void main(string[] args) { map<object,object> m = new hashmap<object,object>(); dog1 d1=new dog1("clover"); //dog1 d2 =new dog1("clover"); m.put(new dog1(), "xyz"); system.out.println(""+m.get(new dog1())); system.out.println(""+m.size()); } }
output:
null
1
can explain me difference between case 1 , case 2??
in case 1 searching same dog1
instance inserted, means hashcode()
implementation object
works fine (in fact, sane implementation work, since using exact same object).
in second case using 2 different instances when inserting , retrieving, doesn't work. object#hashcode()
method typically implemented converting internal address of object integer, means 2 instances pretty have different hash codes.
Comments
Post a Comment