aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hash code question 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 "Hash code question" Watch "Hash code question" New topic
Author

Hash code question

bnkiran kumar
Ranch Hand

Joined: Mar 02, 2006
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???


Kiran Kumar.
Aleksander Zielinski
Ranch Hand

Joined: Nov 11, 2005
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

Joined: Mar 02, 2006
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

Joined: Nov 11, 2005
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hash code question