• Post Reply Bookmark Topic Watch Topic
  • New Topic

HashCodeBuilder Question  RSS feed

 
Raymond Van Eperen
Greenhorn
Posts: 17
Java Mac Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found some interesting behavior while working with a HashMap and wanted to see if someone could shed some light on it.

I am using a HashMap to store a list of transactions keyed by an object that is the transaction owner. The transaction owner class implements equals using EqualsBuilder and hashCode using HashCodeBuilder (see code below) by simply appending the id of the object, and using the two primes 37 and 41 in the HashCodeBuilder constructor.

For reasons beyond this discussion, each transaction contains the owner object and it is a different instance of the class each time. I was expecting that even though they are different instances, they would be considered the same key in the HashMap because equals() would consider them equal (which I tested and is true) and so hashCode() should as well. However, HashCodeBuilder is returning a different value for each instance and I'm not sure why. Can anyone explain?

I looked through the HashCodeBuilder source and didn't see the problem except that it called super.hashCode() which I believe would be executing Object.hashCode() and may be returning something unique to the instance. If this is true, then what is the value of HashCodeBuilder if it can't return a value that is equal to other instances that are logically equal according to the equals() method. Am I just being dumb here?

Here is some code:

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I take it that you're talking about Apache Commons Lang's EqualsBuilder and HashCodeBuilder?

If so, I've also looked at the source, and I believe the mistake you're making is calling builder.hashCode(). That should be builder.toHashCode().
 
Raymond Van Eperen
Greenhorn
Posts: 17
Java Mac Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you confirmed it. I was just being dumb. (And yes, I was talking about the Apache Commons classes)

Thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!