Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reg Hashcodes

 
Vishnu Munnangi
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html

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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic