如何确保hashCode()与equals()一致? [英] How to ensure hashCode() is consistent with equals()?

查看:106
本文介绍了如何确保hashCode()与equals()一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当覆盖java.lang.Object的equals()函数时,javadocs建议,

When overriding the equals() function of java.lang.Object, the javadocs suggest that,


通常需要覆盖每当重写此方法时,hashCode方法,以便维护hashCode方法的一般契约,该方法声明相等的对象必须具有相等的哈希码。

it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

hashCode()方法必须为每个对象返回唯一整数(这在基于内存位置比较对象时很容易,只需返回唯一整数对象的地址)

The hashCode() method must return a unique integer for each object (this is easy to do when comparing objects based on memory location, simply return the unique integer address of the object)

如何覆盖hashCode()方法,使其仅基于每个对象返回唯一整数该对象的特性?

How should a hashCode() method be overriden so that it returns a unique integer for each object based only on that object's properities?


public class People{
   public String name;
   public int age;

   public int hashCode(){
      // How to get a unique integer based on name and age?
   }
}
/*******************************/
public class App{
   public static void main( String args[] ){
       People mike = new People();
       People melissa = new People();
       mike.name = "mike";
       mike.age = 23;
       melissa.name = "melissa";
       melissa.age = 24;
       System.out.println( mike.hasCode() );  // output?
       System.out.println( melissa.hashCode(); // output?
   }
}


推荐答案

它没有说对象的哈希码必须是完全唯一的,只是两个相等对象的哈希码返回相同的哈希码。它完全是合法地让两个不相等的对象返回相同的哈希码。但是,哈希码分布在一组对象上越独特,你将从HashMaps和其他使用hashCode的操作中获得更好的性能。

It doesn't say the hashcode for an object has to be completely unique, only that the hashcode for two equal objects returns the same hashcode. It's entirely legal to have two non-equal objects return the same hashcode. However, the more unique a hashcode distribution is over a set of objects, the better performance you'll get out of HashMaps and other operations that use the hashCode.

诸如IntelliJ Idea之类的IDE具有用于equals和hashCode的内置生成器,它们通常可以为大多数对象提供足够好的代码(并且可能比某些对象更好)手工制作的过于聪明的哈希函数)。

IDEs such as IntelliJ Idea have built-in generators for equals and hashCode that generally do a pretty good job at coming up with "good enough" code for most objects (and probably better than some hand-crafted overly-clever hash functions).

例如,这是Idea为您的People类生成的hashCode函数:

For example, here's a hashCode function that Idea generates for your People class:

public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + age;
    return result;
}

这篇关于如何确保hashCode()与equals()一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆