Altough a hashcode don't has to be unique, the code below
should give in practise practically unique result, when numero or fornitura do not get negative,
which is most likely the case.
There is little chance that this code will not deliver a unique result for
real world data input.
If you don't want to rely on that asumptions, then you have to introduce
your own unique id which you generate when the object is constructed.
For creation of hascodes. See also: Josh Bloch: Effective Java, Second Edition, Item 9
In many cases you don't need a unique id, a suitable hashcode would look as follows:
public int hashCode() {
int result = 17;
result = 31 * result + numero;
result = 31 * result + fornitura;
if (film != null) {
result = 31 * result + film.hashCode();
}
return result;
}
If you need a practically unique code, unique for real world data,
without going the expensive way of creating and looking up unique codes in
data (-base), you could try this:
It uses long instead of int.
(Remember whole life, does not need any garuantee, it's all a question of probability)
public long uniqueCode() {
long result = 17;
result = 31 * result + numero;
result = 31 * result + Long.MAX_VALUE << 16 + fornitura;
result = 31 * result + Long.MAX_VALUE << 32 + stringCode(film);
return result;
}
public static long stringCode(String s) {
if (s == null) return 0;
long h = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
h = 31*h + s.charAt(i);
}
return h;
}