public static void main(String[] args) {
ArrayList <Point> l=new ArrayList <Point> ();
Point p1=new Point(64,91);
Point p2=new Point(78,163);
Point p3=new Point(270,135);
Point p4=new Point(390,180);
Point p5=new Point(390,120);
l.add(p5);
l.add(p4);
l.add(p3);
l.add(p1);
l.add(p2);
for(int i=0;i <l.size();i++){
System.out.print(l.get(i).x);
System.out.print( " ");
System.out.println(l.get(i).y);
}
System.out.println( "================= ");
Collections.sort(l,new myComparator());
for(int i=0;i <l.size();i++){
System.out.print(l.get(i).x);
System.out.print( " ");
System.out.println(l.get(i).y);
}
}
======================================================
public class myComparator implements Comparator {
public int compare(Point a,Point b) {
int x1=a.x;
int x2=b.x;
int y1=a.y;
int y2=b.y;
if(x1 <x2)
return -1;
else
return 1;
}
public int compare(Object arg0, Object arg1) {
// TODO Auto-generated method stub
return 0;
}
}
------解决方案--------------------
public int compare(Object arg0, Object arg1)
public int compare(Point a,Point b)
重載會出問題的
------解决方案--------------------
晕,没看到上面的public int compare(Point a,Point b) ,你写成这样是无效的.
------解决方案--------------------
public class myComparator implements Comparator {
public int compare(Object o1,Object o2) {
Point a, b;
if(o1 instanceof Point){
a = (Point) o1;
} else {
return -1;
}
if(o2 instanceof Point){
b = (Point) o2;
} else {
return -1;
}
int x1=a.x;
int x2=b.x;
int y1=a.y;
int y2=b.y;
if(x1 <x2)
return -1;
else
return 1;
}
}