java中正确重写equals方法

hashCode()和equals()方法,定义在Object类中,这个类是所有类的基类,所以所有的java类都继承了这两个方法。

        hashCode()方法用来给对象获取唯一的一个整数。这个整数被存储在HashTable类似的结构中的位置。默认的,Object类的hashCode()方法返回这个对象存储的内存地址的编号。

      重写equals()方法必须要重写hashCode()方法。if two objects are equal,equal objects must produce the same hash code。However, the third point elaborates that unequal objects need not produce distinct hash codes.

Summed up,equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

public class Test
2.	{
3.		private int num;
4.		private String data;
5.
6.		public boolean equals(Object obj)
7.		{
8.			if(this == obj)
9.				return true;
10.			if((obj == null) || (obj.getClass() != this.getClass()))
11.				return false;
12.			// object must be Test at this point
13.			Test test = (Test)obj;
14.			return num == test.num &&
15.			(data == test.data || (data != null && data.equals(test.data)));
16.		}
17.
18.		public int hashCode()
19.		{
20.			int hash = 7;
21.			hash = 31 * hash + num;
22.			hash = 31 * hash + (null == data ? 0 : data.hashCode());
23.			return hash;
24.		}
25.
26.		// other methods
27.	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值