You must override Object.equals()
and Object.hashCode()
, and also implement the Comparable
interface. This will make your class fully "compliant" when doing any kind of sorting or hashing including using Collections.sort(
), any Map
class, or any Set
class. If there's even a tiny chance that the class will be put in some sort of collection, then it should definitely implement all three of these methods.
public class A implements Comparable<A>{
private String key;
@Override
public boolean equals(Object obj){
if (this == obj) return true;
if (!(obj instanceof A)) return false;
A that = (A)obj;
return this.key.equals(that.key);
}
@Override
public int hashCode(){
return key.hashCode();
}
public int compareTo(A that){
//returns -1 if "this" object is less than "that" object
//returns 0 if they are equal
//returns 1 if "this" object is greater than "that" object
return this.key.compareTo(that.key);
}
}
Keep in mind that if two objects are equal, then:
- their hash codes must also be equal and
compareTo()
must return 0.