《Effective JAVA学习笔记》之 equals()

import java.util.Arrays;

class Person {
	String name;
	int birthYear;
	byte[] raw;
	
	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof Person))
			return false;

		Person other = (Person) obj;
		return this.name.equals(other.name) && this.birthYear == other.birthYear && Arrays.equals(this.raw, other.raw);
	}
	
	@Override
	public int hashCode() {
		return name.hashCode()  + Arrays.hashCode(raw);
	}
}

如何理解:当你创造出了一个新类,你固然要制定某些规则。好比:新类new出来的两个实例,怎么样才能算一摸同样。这个相等规则就是equals()。 hashCode至关于这个类的身份ID,你能够自定义。固然不一样的实例,hashCode确定是不同的。html

  • 参数必须是Object类型,不能是外围类。java

  • foo.equals(null) 必须返回false,不能抛NullPointerException。(注意,null instanceof 任意类 老是返回false,所以上面的代码能够运行。)api

  • 基本类型域(好比,int)的比较使用 == ,基本类型数组域的比较使用Arrays.equals()。数组

  • 覆盖equals()时,记得要相应地覆盖 hashCode(),与 equals() 保持一致。数据结构

  • 参考: java.lang.Object.equals(Object)oracle

  • 当x和y两个对象具备x.equals(y) == true ,你必需要确保x.hashCode() == y.hashCode()。ide

  • 根据逆反命题,若是x.hashCode() != y.hashCode(),那么x.equals(y) == false 一定成立。性能

  • 你不须要保证,当x.equals(y) == false时,x.hashCode() != y.hashCode()。可是,若是你能够尽量地使它成立的话,这会提升哈希表的性能。this

  • hashCode()最简单的合法实现就是简单地return 0;虽然这个实现是正确的,可是这会致使HashMap这些数据结构运行得很慢。code

  • 参考:java.lang.Object.hashCode()


http://www.cnblogs.com/xudong-bupt/p/3960177.html

相关文章
相关标签/搜索