Given the following class definition
public class ValuePair implements Comparable{
private int iLookUp;
public ValuePair(int iLookUP, String sValue){
this.iLookUp=iLookUp;
}
public void setLookUp(int iLookUp){
this.iLookUp = iLookUp;
}
public int getLookUp(){
return iLookUp;
}
public boolean equals(Object o){
Integer iwLookUp = (Integer) o;
if(iLookUp == iwLookUp.intValue()){
return true;
}
return false;
}
public int compareTo(Object o) {
ValuePair vp = (ValuePair) o;
Integer iwLookUp= new Integer(vp.getLookUp());
if(iwLookUp.intValue() < iLookUp){
return -1;
}
if(iwLookUp.intValue() > iLookUp){
return +1;
}
return 0;
}
}
Which of the following would be valid hashCode methods?
public int hashCode() {
return (int) System.currentTimeMillis();
}
public char hashCode(){
reuturn (char) iLookUp;
}
public int hashCode(){
return iLookUp;
}
public int hashCode(){
return iLookUp * 100;
}
The Correct Answer is
3)
public int hashCode(){
return iLookUp;
}
public int hashCode(){
return iLookUp * 100;
}
The value returned by the hashCode method must be an integer which rules out option 2 which returns a char value. Option 1 returns a version of the time in milliseconds which is certain to return a different value during a single run of the program, thus breaking one of the specific requirements of the contract for hashCode. The correct options, 3 and 4 may not be particularly good versions of the hashCode method but they are consistent with the equals value and return the correct data type.
Não entendi essa questão… Se o método equals() já não está apropriado, como podemos ter uma implementação do hashCode() apropriada??
Alguém entendeu essa questão?