是否建议使用哈希码来确定Java中的相等性?

k4k*_*uz0 7 java equals hashcode

假设我们有一个hashcode()函数,然后在我们的equals()方法中使用它来确定两个对象的相等性.这是允许/接受的方法吗?

假设我们使用哈希码的简单实现.(例如,一些实例变量乘以素数.)

Stu*_*ske 8

这是检查相等性的可怕方法,主要是因为对象不必等于返回相同的哈希码.

您应该始终使用equals方法.

一般规则是:

如果对象a和b的equals方法返回true,则hashCode方法必须为a和b返回相同的值.

这并不意味着,如果a和b的hashCode方法返回相同的值,则equals方法必须为这两个实例返回true.

例如:

public int hashCode(){
  return 5;
}
Run Code Online (Sandbox Code Playgroud)

是一个有效的,但无效的哈希码实现.

编辑:

在equals方法中使用它将是这样的:

public class Person{

private String name;

public Person(String name){ this.name = name;}

public String getName(){ return this.name;}

@Override
public boolean equals(Object o){
  if ( !(o instanceof Person)){ return false;}
  Person p = (Person)o;
  boolean nameE = this.name == null ? p.getName() == null : this.name.equals(p.getName());
  boolean hashE = nameE ? true : randomTrueOrFalse();
  // the only moment you're sure hashE is true, is if the previous check returns true.
  // in any other case, it doesn't matter whether they are equal or not, since the nameCheck returns false, so in best case, it's redundant
  return nameE && hashE;
}

@Override
public int hashCode(){
  int hash = generateValidHashCode();
  return hash;
}

}
Run Code Online (Sandbox Code Playgroud)