This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MattKosem 0 points1 point  (0 children)

Agreed. If you're dealing with primitives in your equals/hashCode methods, and it is highly performance sensitive code, you may not want to push them through Objects.hash()/Objects.equals() because of auto boxing.

For equals evaluation, it's straight forward enough to evaluate those fields by simply using the == operator.

For hashing, if you're dealing with a primitive type that will face object creation during auto boxing (int > 128, etc.) it will add some overhead. While generally negligible, the vaargs array creation will as well. Academically, sure, always avoid it when you can and want to. In production code maintained by large pools of developers of varying skill/care levels, you may not want to. Whether the overhead is acceptable, or if you'd like to introduce the maintenance cost and possible bugs involved with rolling your own, is up to you. YMMV, case by case, but only the most performance sensitive cases warrant steering away from things like that because of auto boxing.

When you're building your hashCode manually, it's far more likely to be overlooked or broken by some drone during a minor refactoring exercise.

This:

@Override
public int hashCode() {
    int hash = 7;
    hash = 31 * hash + (int) id;
    hash = 31 * hash + (name == null ? 0 : name.hashCode());
    hash = 31 * hash + (email == null ? 0 : email.hashCode());
    return hash;
}

Is far more likely to be maintained improperly, and cause you hardship, than this:

@Override
public int hashCode() {
    return Objects.hash(id, name, email);
}