anto150192
anto150192

Reputation: 537

I need to create a unique code from value variables of a java object

I've thought about:

codeUnique=Math.abs(film.hashCode()+((Integer)numero).hashCode()+
                    ((Integer)fornitura).hashCode();

But use the hashCode is not ok because it isn't unique, it changes in time. Variables are these:

    private int numero;
    private String film;
    private int fornitura;

Thanks!

Upvotes: 0

Views: 449

Answers (1)

AlexWien
AlexWien

Reputation: 28737

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;
  }

Upvotes: 2

Related Questions