tags:

views:

150

answers:

2

Hi all,

In relation to this question (http://stackoverflow.com/questions/1074530/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

+2  A: 

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
yes it's my aim of course. Thanks
Manuel Selva
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
Good to know, but HashMap is not the only code to make use of hashCode() so distribution could be a problem.
GaryF
+5  A: 

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 for emphasizing that it's *not* uniqueness :-). Well said.
Tom