我需要从java对象的值变量创建一个唯一的代码

时间:2015-09-22 17:46:22

标签: java object hashcode unique-key

我已经想过:

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

但是使用hashCode是不行的,因为它不是唯一的,它会随时间而变化。变量是这些:

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

谢谢!

1 个答案:

答案 0 :(得分:2)

Altough哈希码不必是唯一的,下面的代码 在实践中应该给出实际上独特的结果,当数字或fornitura没有得到否定时, 最有可能的情况。 此代码几乎不可能提供唯一的结果 现实世界的数据输入。

如果您不想依赖这些假设,那么您必须介绍  您构建对象时生成的唯一ID。

用于创建hascodes。另见:Josh Bloch:Effective Java,Second Edition,Item 9

在许多情况下,您不需要唯一的ID,合适的哈希码将如下所示:

public int hashCode() {
  int result = 17;
  result = 31 * result + numero;
  result = 31 * result + fornitura;
  if (film != null) {
    result = 31 * result + film.hashCode();
  }
  return result;
}

如果您需要一个实际唯一的代码,对于真实世界数据是唯一的 没有采用昂贵的方式创建和查找唯一代码  数据(-base),你可以试试这个: 它使用long而不是int。

(记住一生,不需要任何代表,这都是概率问题)

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