Which of the following will fulfill the equals() and hashCode() contracts for this class? (Choose all that apply.)
Answers are:
A. return ((SortOf)o).bal==this.bal;
B. return ((SortOf)o).code.length()==this.code.length();
C. return ((SortOf)o).code.length()*((SortOf)o).bal==this.code.length()*this.bal;
D. return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate==this.code.length()*this.bal*this.rate;
Correct Answers: C & D
EXPLANATION:
C and D are correct. The equals() algorithm must be at least as precise in defining what "meaningfully equivalent" means as the hashCode() method is.
A and B are incorrect because these equals() implementations would allow instances to be equal that hashCode() would not see as equal.
Stephan van Hulst wrote:None of the answers are correct. The equals() contract explicitly states that x.equals(null) should return false. None of the implementations fulfill this requirement.
But suppose we insert a null check that returns false? Then it does appear that D is incorrect.For any non-null reference value x, x.equals(null) should return false.
Dennis Deems wrote:But suppose we insert a null check that returns false? Then it does appear that D is incorrect.
Joanne
Helen Ma wrote:Hi, Sebati,
Do you think the answer is only C. A few people on the forum feel that the only answer is C, not D. I don't think we need to worry about x.equal (null) for the exam. If the string code is null, the code.length will throw a null pointer exception, that is not the objective of this question.
OCPJP 6, OCMJD
Class Chili{
String color ;
String hotness;
public Chili (String c, String h){ color=c; hotness=h;}
public boolean equals(Object o){
if ( ((Chili)o ).color = color && ((Chili)o).hotness = hotness
return true;
else
return false;
}
public int hashCode(){
return 100;
}
Chili c = new Chili("red", 1);
Chili c1 = new Chili ("green",2) ;
public int hashCode(){
Math.random(100); // for example..... I am not sure if this syntax is right.
}
Chili c = new Chili ("red", 1); Chili c1 = new Chili("red", 1);
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |