• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hasshcode for Reference variable and Object  RSS feed

 
Nirmal Mukundan
Ranch Hand
Posts: 37
Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a Java bean in which I have not overridden the hashcode(). I have added the instance of the bean as a key in a HashMap() as given below.


Since I have not implemented the hashcode(), the value would be null and after implementation I get the value "Test". I understand this part.

But with the same condition of not implementing hashcode(), if I put into the HashMap as below, then I am getting the value "Test". Even though I have not implemented hashcode(), how do I get the value.



I tried to understand this by trying many examples, but failed. Could you please explain this.

Regards
Nirmal Mukundan
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no such thing as a hash code for a reference variable. A variable is simply a reference, which points to a particular object. That object can calculate a hash code. I presume you are already familiar with writing hashCode() methods.
You are also confusing overriding and implementing. You said
Nirmal Mukundan wrote:Hello,

I have a Java bean in which I have not overridden the hashcode(). . . . Since I have not implemented the hashcode(), . . .
You have implemented the hashCode method; if you have not overridden it, it is implicitly implemented, but as the version inherited from java.lang.Object. You can’t not implement a hashCode() method, and you can’t un‑implement it.
If you use the same object twice, that will have the same hash code, so you will get the value back. Remember hashCode() ≡ equals(). If the two objects are equal, they have the same hash code. An object is always equal to itself, so it has the same hash code as itself. So those two uses of the same StudentVO object both have the same hash code. They must have the same hash code; if you haven’t overridden the hashCode() method there is no code to change the hash code.
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't override hashcode() you can't get null, hashcode() returns an int.

The keys aren't found exclusively on the hashcode value. The hashcode value is used to find the bucket containing (home in on the location of) the key and the equals method is used to determine if a key in that bucket is the required key. ie numerous objects could have the same hashcode but be different keys. I suggest you read the API docs for Object and look at the contract between the equals method and the hashcode method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!