Object类中的equals方法只有在同一个对象比较时才会返回true,即if(obj1==obj1);
如果一新写的一个类没有重写equals方法,则调用父类equals方法。
在使用容器的remove,contains等方法时,一定要重写相应自己写的类的equals和hashcode。
当equals被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码
public class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Object o){
if(!(o instanceof Point))
return false;
Point p = (Point)o;
return p.x == x && p.y == y;
}
}