programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Hash code question

bnkiran kumar
Ranch Hand
Posts: 176
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()) & (i2 == ((A)obj).getI2());
}
return false;
}
public int hashCode() {
// Insert statement here.
}}

If inserted at the specified location, which of the following statements would produce the most efficient hashCode method?

a. return 31;
b. return getI1();
c. return getI2();
d. return getI1() + getI2();
e. return 31 * getI1() + getI2();
f. None of the above

the answer is e, i think a is also correct because it is consistent.
can any body answer???

Aleksander Zielinski
Ranch Hand
Posts: 127
Hashcode is getting more efficent when the possibility of obtaining two same hashcodes is getting smaller, it's opposite to answer a), consistent hashcode is the least efficient hashcode.

bnkiran kumar
Ranch Hand
Posts: 176
but for this ,they have given a and b as answers, why a is correct!!!

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();

Aleksander Zielinski
Ranch Hand
Posts: 127
Hashcode contract means that if you compare two object using equals method, then your hashcode must return the same integer in orded to fulfill the contract, it doesn't mean it has to be efficient, that's what they asked about in the previous question.