If you have a class Foobar
:
public class Foobar {
private final int myInt;
... constructor ...
public int hashCode() {
return Integer.hashCode(myInt);
}
}
Since Java 8, the method Integer.hashCode
exists. Otherwise, you can use Integer.valueOf(myInt).hashCode()
.
Note: in the question, you'll read that hashCode and equals should not be based on mutable field, that's why I put final
in declaration of myInt
. In practice, it depends on use case (for example, Set
based on a generated id in OneToMany
in JPA) and where come your data.
Now as for the "good" hashCode
, since it is used for hash based collection (map, set), you need to have a good repartition: imagine you return myInt % 1000
, which means a value between 0 and 999; then this HashSet
will not be efficient:
Set<Integer> set = new HashSet<Integer>(20); // initial capacity of 20
set.add(0); // 0 [[0]]
set.add(1000); // 0 [[0, 1000]]
set.add(2000); // 0 [[0, 1000, 2000]]
set.add(3000); // 0 [[0, 1000, 2000, 3000]]
set.add(20); // 20 -> 20 % 20 => 0 [[0, 1000, 2000, 3000, 20]]
set.add(21); // 1 -> 1 % 20 => 1 [[0, 1000, 2000, 3000, 20], [1]]
In comments, and in the following order:
hashCode
returned by myInt % 1000
- if not trivial,
index
in internal HashSet
array.
- content of
HashSet
The first four values (0 to 3000) will be stored at the same place, 20 will also be stored at the same place, but 21 at another place. Looking up a value require to iterate over the five values.
- For Java Integer, it is the value (here, you could return
myInt
instead of calling Integer.hashCode
)
- For Java Long, it is some xor (using ^); see
Long.hashCode
.
- For collection, it is in general the sum of
P * o.hashCode()
where P is a prime number; see Arrays.hashCode
But I don't remember the exact answer as to why you should use a prime number.