这里的点 point(2,3)是两个不同的对象,肯定是不能输出“-1”的这样修改class Point{
public int x ,y;
String direction="";
Point(int x, int y){
this.x=x;
this.y=y;
}
public boolean equals(Point p){
return (this.x==p.x)&&(this.y==p.y);
}
}
public class test {
public static void main(String[] args) {
Vector v= new Vector(); Point a = new Point(1,1);
Point b = new Point(2,3);
v.add(a);
v.add(b);
System.out.println(v.indexOf(b));
}
public int x ,y;
String direction="";
Point(int x, int y){
this.x=x;
this.y=y;
}
public boolean equals(Point p){
return (this.x==p.x)&&(this.y==p.y);
}
}
public class test {
public static void main(String[] args) {
Vector v= new Vector(); Point a = new Point(1,1);
Point b = new Point(2,3);
v.add(a);
v.add(b);
System.out.println(v.indexOf(b));
}
System.out.println(v.indexOf(new Point(2,3)));
改为:
Point p= new Point(2,3);
v.add(p);
System.out.println(v.indexOf(p));
修改结果如下:
public boolean equals(Object o){
return (o instanceof Point)&&(this.x==((Point)o).x)&&(this.y==((Point)o).y);
}
原来需要覆盖equals这个方法,而不算是equal。
public boolean equals(Object obj){
if(!(obj instanceof Point))
return false;
Point p = (Point)obj;
return (this.x==p.x)&&(this.y==p.y);
}
//这个算法可以随便写,但是一定要保证
// 如果 a.equals(b) 则一定可以推出:a.hashCode() == b.hashCode();
// 反之,则未必。
public int hashCode() {
return this.x << 8 & this.y;
}