我写了一个类,并复写了equals方法,
Position p = new Position(5, 5);;
Position p1 = new Position(7, 6);;
执行
p.equals(p1);
返回true;
但是 Set<Position> set = new HashSet<Position>();
set.add(p1);
set.contains(p);//返回false!!!!!!!why????!!
查了jdk文档
/////////////////////
boolean contains(Object o) 如果 set 包含指定的元素,则返回 true。更确切地讲,当且仅当 set 包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时返回 true。
////////////////////我已经复写了equals了!为什么根本就没有执行我复写的方法呀?
public class Position {
int x, y;
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if (obj == null)
return false;
System.out.println("I'm in equals!!!!!!!!!!");
boolean re = obj.getClass().equals(this.getClass());
if (re) {
Position p = (Position) obj;
if ((p.x != this.x) || (p.y != this.y))
re = false;
} return re;
} Position(int x, int y) throws OutException {
if (x < 0 || y < 0 || x > 7 || y > 7) {
throw new OutException();
} else {
this.x = x;
this.y = y;
} }
}
Position p = new Position(5, 5);;
Position p1 = new Position(7, 6);;
执行
p.equals(p1);
返回true;
但是 Set<Position> set = new HashSet<Position>();
set.add(p1);
set.contains(p);//返回false!!!!!!!why????!!
查了jdk文档
/////////////////////
boolean contains(Object o) 如果 set 包含指定的元素,则返回 true。更确切地讲,当且仅当 set 包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时返回 true。
////////////////////我已经复写了equals了!为什么根本就没有执行我复写的方法呀?
public class Position {
int x, y;
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if (obj == null)
return false;
System.out.println("I'm in equals!!!!!!!!!!");
boolean re = obj.getClass().equals(this.getClass());
if (re) {
Position p = (Position) obj;
if ((p.x != this.x) || (p.y != this.y))
re = false;
} return re;
} Position(int x, int y) throws OutException {
if (x < 0 || y < 0 || x > 7 || y > 7) {
throw new OutException();
} else {
this.x = x;
this.y = y;
} }
}
Position p1 = new Position(5, 5);;
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + x;
result = PRIME * result + y;
return result;
}
public int hashCode()方法。
HashSet的contains返回true,当且仅当equals返回true并且hashCode返回相等的值。另外,楼上说的问题是不是笔误?
不过6这个系数和你的点的取值范围有关.