Given: 11. x = 0; 12. if (x1.hashCode() != x2.hashCode() ) x = x + 1; 13. if (x3.equals(x4) == false ) x = x + 10; 14. if (x5.equals(x6) == true ) x = x + 100; 15. if (x7.hashCode() == x8.hashCode() ) x = x + 1000; 16. System.out.println("x = " + x); If the output is "x = 1111", which of the following statements will always be true? (Choose all that apply.)
There are 4 answer options and correct one is given below.(Other options I could not remember as ans guide dont provide them and its painful to go thru all the questions again looking for one question.)
Correct Answer: x5.hashCode() == x6.hashCode()
Question says that output is X=1111 . As per the equals() contract given ans is correct. But my doubt is then why is it mentioning about 1111 output?
Does that mean we should not consider that point?
If someone has already solved this Q then they can understand why I am asking this.
I checked all 4 answers because it evaluated to 1111. But only ans true is the given one and in that case x becomes 100 . (Initial x =0 and all other cases were in if() statement.)
Originally posted by Vivian Josh: No, I fell for the same trap
I checked all 4 answers because it evaluated to 1111. But only ans true is the given one and in that case x becomes 100 . (Initial x =0 and all other cases were in if() statement.)
Not really, It's not the trap. please give the options. I can explain them
Hi, The question was trying to figure out your understanding on hashcode and equals contract.
All the conditions are valid, choose the one that is correct from the answers
x1.hashCode() != x2.hashCode() x = x + 1; x3.equals(x4) == false x = x + 10; x5.equals(x6) == true x = x + 100; x7.hashCode() == x8.hashCode() x = x + 1000; 16. System.out.println("x = " + x); ----> 1111
1111 can be got only if all the conditions are met, indirectly hinting that the above comparisons on hashcode and equals result in true, Now choose from the answers which one is correct.
Going condition by condition,
HashCode and Equals Contract ------------------------------ The hashcode and equals contract states for any two objects x,y that if (x.hashcode() == y.hashcode() ){ x.equals() MAY_BE_EQUALS_TO y.equals() }
if (x NOT_EQUALS y))){ x.hashcode() MAY_BE_EQUALS_TO y.hascode() }
if (x EQUALS y)){ x.hashcode() SHOULD_BE_EQUALS_TO y.hascode() }
if (x.hashcode() != y.hashcode() ){ x.equals() SHOULD_NOT_EQUALS_TO y.equals() }