hashCode()方法
其他
2019-01-25 20:48:20
阅读次数: 0
如果两个元素的equals方法返回true,但他们的hashCode返回值不相等,HashSet将会把它们存储在不同的位置,但依然可以添加成功。
对于存放在Set容器中的对象,对应的类一定要重写equals和hashCode(Object obj)方法,以实现对象相等规则。
重写hashCode方法的原则:
-
在程序运行时,同一个对象多次调用hashCode方法应该返回相同的值
-
当两个对象的equals方法比较返回true时,这两个对象的hashCode方法的返回值也相等
-
对象中用作equals方法比较的Field,都应该用来计算hashCode值
-
package com.xatu.集合;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
class Point{
int x,y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
//100 200
return Integer.parseInt(x+" "+y);
}
@Override
public boolean equals(Object other) {
if (other instanceof Point) {
Point otherPoint = (Point) other;
if(this.x== otherPoint.x && this.y == otherPoint.y)
{
return true;
}
}
return false;
}
}
public class hashCodeTest {
@Test
public void test() {
Point p1 = new Point(100, 200);
Point p2 = new Point(100, 200);
System.out.println(p1.equals(p2));
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
Set<Point> set = new HashSet<Point>();
set.add(p1);
set.add(p2);
System.out.println(set);
}
}
转载自blog.csdn.net/dagedeshu/article/details/86620044