We will discuss some important methods in the Object class itself which is used for collections.
Below 2 methods will be discussed here.
1. boolean equals(Object o): This method is used for checking 2 objects are equal or not.
2. int hashCode(): This method is used to get the hash key [bucket in the hash table]
Say 2 objects of below A, a1 and a2 has to be added into some Set. How JVM will make sure 2 objects are not duplicate of each other? JVM will use the equals method to decide this.
Example:
======
class A{
int i;
A(int in){
this.i=in;
}
public boolean equals(Object o){
if(o != null && o instanceof A && ((A) o).getI()==this.i){
return true;
}
return false;
}
public int hashCode(){
return i%10001;
}
int getI(){
return i;
}
void setI(int in){
this.i=in;
}
}
======
But is equals method sufficient for 2 objects to be equal? The answer is no. Here both the object should have same hashCode returned by the int hashCode()
This hashCode() method is used for bucketing in Hash implementations of Java e.g. HashMap, Hashtable, HashSet.
So for the above a1 and a2 objects, below checks are followed to check equal or not.
1. if a1 and a2 return same hashCode
then both are in the same bucket of hash table. Now check for equals(Object o) method.
2. else
return false(objects are not equal)
Below 2 methods will be discussed here.
1. boolean equals(Object o): This method is used for checking 2 objects are equal or not.
2. int hashCode(): This method is used to get the hash key [bucket in the hash table]
Say 2 objects of below A, a1 and a2 has to be added into some Set. How JVM will make sure 2 objects are not duplicate of each other? JVM will use the equals method to decide this.
Example:
======
class A{
int i;
A(int in){
this.i=in;
}
public boolean equals(Object o){
if(o != null && o instanceof A && ((A) o).getI()==this.i){
return true;
}
return false;
}
public int hashCode(){
return i%10001;
}
int getI(){
return i;
}
void setI(int in){
this.i=in;
}
}
======
But is equals method sufficient for 2 objects to be equal? The answer is no. Here both the object should have same hashCode returned by the int hashCode()
This hashCode() method is used for bucketing in Hash implementations of Java e.g. HashMap, Hashtable, HashSet.
So for the above a1 and a2 objects, below checks are followed to check equal or not.
1. if a1 and a2 return same hashCode
then both are in the same bucket of hash table. Now check for equals(Object o) method.
2. else
return false(objects are not equal)
No comments:
Post a Comment