This is repetedly asked in interview question. ....
How HashMap internally works ?
class Test{
int x;
Test(int x){
this.x=x;
}
public int hashCode(){
System.out.println("hashCode() Called");
return x;
}
public boolean equals(Object o){
System.out.println("equals(-) Called");
return this.x==((Test)o).x;
}
public String toString(){
return "Test("+x+")";
}
}
class HSDemo{
public static void main(String... arg){
HashSet<Test> hs=new HashSet<>();
Test t1=new Test(5);
System.out.println("Here hashCode called to chk wether there is a bucket with hashCode 5 or not");
hs.add(t1);
//here equals method not called because first hashCode is called bucket found
//den in that bucket comparison starts first compare on the basis of refrence
//With the help of == operator so in bucket only one element is there and second
//element is discarded due to same refrence equals not called
int x;
Test(int x){
this.x=x;
}
public int hashCode(){
System.out.println("hashCode() Called");
return x;
}
public boolean equals(Object o){
System.out.println("equals(-) Called");
return this.x==((Test)o).x;
}
public String toString(){
return "Test("+x+")";
}
}
class HSDemo{
public static void main(String... arg){
HashSet<Test> hs=new HashSet<>();
Test t1=new Test(5);
System.out.println("Here hashCode called to chk wether there is a bucket with hashCode 5 or not");
hs.add(t1);
//here equals method not called because first hashCode is called bucket found
//den in that bucket comparison starts first compare on the basis of refrence
//With the help of == operator so in bucket only one element is there and second
//element is discarded due to same refrence equals not called
System.out.println("\nTrying to add objects with same refrence but Set doesnt allow");
hs.add(t1);
System.out.println(hs);
hs.add(t1);
System.out.println(hs);
System.out.println();
//but here firs hashCode called buck found
//den == operator called to chk refrence wise duplicacy
//nd unfortunately refrence is diff so now equals will called
//to chk data wise duplicacy and data is same so this is also discarded
Test t2=new Test(5);
System.out.println("\nTrying to add objects with different refrence and same data but Set doesnt allow");
hs.add(t2);
System.out.println(hs);
}
//den == operator called to chk refrence wise duplicacy
//nd unfortunately refrence is diff so now equals will called
//to chk data wise duplicacy and data is same so this is also discarded
Test t2=new Test(5);
System.out.println("\nTrying to add objects with different refrence and same data but Set doesnt allow");
hs.add(t2);
System.out.println(hs);
}
}
Comments
Post a Comment