wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reg Hashcodes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reg Hashcodes" Watch "Reg Hashcodes" New topic

Reg Hashcodes

Vishnu Munnangi
Ranch Hand

Joined: Sep 28, 2004
Posts: 114
Hi EveryOne,
This is one of the Questions from the Dan's Mock Exam.
Please go through the code...

class A {
int i1, i2;
public void setI1(int i) {i1 = i;}
public int getI1() {return i1;}
public void setI2(int i) {i2 = i;}
public int getI2() {return i2;}
public A(int ii1, int ii2) {i1 = ii1; i2 = ii2;}
public boolean equals(Object obj) {
if (obj instanceof A) {
return (i1 == ((A)obj).getI1());
return false;
public int hashCode() {
// Insert statement here.

Which of the following statements could be inserted at the specified location without violating the hash code contract?

a. return 31;
b. return getI1();
c. return getI2();
d. return 31 * getI1() + getI2();

The answers given are a,b.
I am not able to understand, how a can be the answer. I might not have understood the concept.
Can any one explain me about the answers to this question.

Thanks in advance.
marc weber

Joined: Aug 31, 2004
Posts: 11343

The hashCode contract basically says that if two objects are equal as defined by the equals(Object) method, then they need to return the same hashCode value.

See hashCode method under the Object API:

Note that unequal objects are not required to return different hashCode values, although the hashing would be more efficient if they did.

In this question, the equals(Object) method is defined to return true if the objects being compared are both instances of class A and they have the same value for int i1. Note that the value of int i2 has nothing to do with this definition of equals.

Therefore, the only variable that can be used to calculate class A's hashCode function is i1. The variable i2 cannot be used, because then instances of class A that are equal (as defined by the equals method) might not return the same hashCode, and the hashCode contract would be broken. This eliminates options c and d, because they both use i2.

Option a is a poor hashCode method because a constant fails to differentiate between different objects, but it does comply with the hashCode contract: Equal objects will return the same hashCode.

[ October 18, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link: http://aspose.com/file-tools
subject: Reg Hashcodes
It's not a secret anymore!