0

In relation to this question (Efficient hashCode() implementation) I have one more question.

I have a "value" class which instances are persisted in a database. Thus this class's instances all have a unique ID.

As a consequence I implemented the hash code method (and related equals method) simply by returning this id.

When using Eclipse hashcode generator and telling Eclipse to use only the ID attribute for generation I have the following method:

    @Override
    public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + id;
            return result;
    }

I think simply returning id is more efficient since I KNOW this id is unique. Am I right ?

Thanks in advance

Community
  • 1
  • 1
Manuel Selva
  • 18,554
  • 22
  • 89
  • 134
  • If result is 1, why do you mulply by result. You function is effectively "return 31 + id;". – Tom Jul 02 '09 at 14:26
  • Which by the way, you might as well get rid of the 31, because it doesn't alter the distribution of the id. In short, the hashcode you implemented does not do anything special, and you should just return id. That being said, I'm not sure what would be "better". – Tom Jul 02 '09 at 14:28

2 Answers2

5

It's not the uniqueness of the ID that makes this the right thing to do - it's the fact that that's used for the equality check and it's the only thing used for the equality check.

The boilerplate from Eclipse is really only relevant when you're using multiple fields for equality.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

If you're aiming for identity uniqueness then absolutely, yes.

Keep in mind though that since you're (probably) not randomly distributing your values through the possible range of your hash function (i.e. all the values of int) that performance might be a problem for any code that relies on hashes being evenly distributed.

P.s. That "probably" comes from my assumption that these unique ints are probably identity values in your db. If they really are randomly distributed, ignore my caveat.

GaryF
  • 23,950
  • 10
  • 60
  • 73
  • 1
    java.util.HashMap already applies a supplemental hash function to the hashcode to improve distribution, so the distribution shouldn't be a problem. – Michael Myers Jul 02 '09 at 14:24
  • Good to know, but HashMap is not the only code to make use of hashCode() so distribution could be a problem. – GaryF Jul 02 '09 at 15:13