重写equals方法

hashCode()和equals()方法,定义在Object类中,这个类是所有类的基类,所以所有的java类都继承了这两个方法。
  • hashCode()方法用来给对象获取唯一的一个整数。这个整数被存储在HashTable类似的结构中的位置。默认的,Object类的hashCode()方法返回这个对象存储的内存地址的编号。
public class Test
{
	private int num;
	private String data;

	public boolean equals(Object obj)
	{
		if(this == obj)
			return true;
		if((obj == null) || (obj.getClass() != this.getClass()))
			return false;
		// object must be Test at this point
		Test test = (Test)obj;
    	return num == test.num &&
    	(data == test.data || (data != null && data.equals(test.data)));
	}

	public int hashCode()
	{
		int hash = 7;
		hash = 31 * hash + num;
			hash = 31 * hash + (null == data ? 0 : data.hashCode());
		return hash;
	}
		// other methods
}

原文地址:https://www.cnblogs.com/tonghaolang/p/7141990.html