代码如下:importjava.util.Arrays;importjava.util.Comparator;classPoint{privateintx;privateinty;publicPoint(int_x,int_y){x=_x;y=_y;}publicintgetX(){returnx;}publicintgetY()...
代码如下:
import java.util.Arrays;
import java.util.Comparator;
class Point
{
private int x;
private int y;
public Point(int _x, int _y)
{
x = _x;
y = _y;
}
public int getX(){return x;}
public int getY(){return y;}
public void print(){System.out.println("x = " + x + "\ty = " + y);}
public boolean equals(Object obj)
{
if (this == obj)return true;
if (!(obj instanceof Point))return false;
Point temp = (Point)obj;
return (x == temp.x && y == temp.y);
}
}
class PointComparator implements Comparator
{
public int compare(Point p1, Point p2)
{
if (p1.equals(p2))return 0;
else if (p1.getX() > p2.getX())return 1;
else if (p1.getX() < p2.getX())return -1;
elsereturn p1.getY() > p2.getY() ? 1 : -1;
}
}
public class Test
{
public static void main(String[] args)
{
Point[] ps = {new Point(8, 9), new Point(2, 7),
new Point(6, 5), new Point(6, 3)
};
Arrays.sort(ps, new PointComparator());
for (Point p : ps)
p.print();
}
}
代码没有错,有点不明白: 不是一个类如果实现一个接口,就得重写这个接口的全部方法吗?Comparator接口里有两个方法,一个是compare,另一个是equals,但在上面这个PointComparetor类里并没有重写equals方法,虽然Point类重写了这个方法,但这根本就是两个不同的类嘛,请高手指教,谢谢!
展开