• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode method

 
janki tangeda
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class B {
private int i1;
public int hashCode() {return 1;}
}
class C {
private int i1;
public int hashCode() {return -1;}
}
class D {
private int i1;
public int hashCode() {return i1;}
}

Why are the first two implementations of hashcode not appropriate though it won't violate the hashcode error and won't give any error?
 
Anurag Jain
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first 2 methods, the return value will be identical for all objects, thus it will be inefficient. In the 3rd case the value will be based on the variable which will be less likely to return same hash code.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Anuraag"-
Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it

here.

Thanks! and welcome to the JavaRanch!

Mark
 
Anurag Jain
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I updated it, thanks for pointing out!
 
janki tangeda
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it..thanks Anurag
 
shyam ramineni
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have tried the below code.

I think the third option is also not correct as hashCode() method must consistently return the value for a object.
Am I right or wrong?

Thanks
Shyam Ramineni
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic