0

I am considering using Eclipse generated HashCode and I have a basic doubt (using it for the first time). Why does the hashCode in the below code snippet use the result field? I feel it is redundant and would like to understand what possible reasons could cause it to being there

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((projectId == null) ? 0 : projectId.hashCode());
    return result;
}
HopeKing
  • 3,317
  • 7
  • 39
  • 62
  • 1
    Generating hashcodes is difficult, that is being used to try and generate a good distribution of hashes. – Elliott Frisch Jul 01 '17 at 13:31
  • 1
    You probably only have one field right now, this will make more sense if you have more than one field that is used in the hash code (in essence the code that generates this simply iterates over all fields and repeats the same `result = prime * ...` for each field) – Mark Rotteveel Jul 01 '17 at 13:42
  • Yes, that makes sense. – HopeKing Jul 01 '17 at 13:44
  • 1
    Sometimes it makes sense to do it yourself. In this case, `return Objects.hash(projectId);` is probably cleaner... – assylias Jul 01 '17 at 14:20
  • This is a decent hash function. I'm sure the main reason it uses the variable `result` the way it does is to keep the Eclipse code generator simple. When you generate a hash on multiple fields, it will just add a line for each field that recomputes the value of `result`. As others have said, the compiler is very likely to produce the same bytecode whether this intermediate variable is used or not. If you don't like the way it looks, by all means make it pretty by hand. That's what I usually do, since it's harder to read than it needs to be. – Gene Jul 01 '17 at 15:35

1 Answers1

1

Donald Knuth said "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil".

Regarding your question: java JIT compiler is so smart, that it will remove all unnecessary variables and calculations.

So you should concentrate on writing understandable, readable and maintainable code. You have to fix performance problems when they appear.

Gene
  • 46,253
  • 4
  • 58
  • 96
Denis Kokorin
  • 887
  • 8
  • 17