首先创建一个类,也就是类似C++中的结构体。
class node{
int x, y;
}
之后我们要重写一下Comparator接口,中的compare方法:
class mycompare implements Comparator<node>{
@Override
public int compare(node o1, node o2) {
if(o1.x == o2.x){
return o1.y > o2.y?-1:1; //返回y较大的
}
return o1.x > o2.x?-1:1; //返回x较大的
}
}
最后调用:
public static void main(String[] args) {
node stu[] = new node[4];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 4; i++){
stu[i] = new node();
stu[i].x = sc.nextInt();
stu[i].y = sc.nextInt();
}
Arrays.sort(stu, 1, 4, new mycompare()); //对部分元素排序,区间左闭右开
for(node s: stu){
System.out.println(s.x + "\t" + s.y);
}
}