通常可以使用 Comparator 或 Comparable ,以简单的方式实现对象排序或自定义排序。
一、Comparator
强行对某个对象 collection 进行整体排序的比较函数,可以将 Comparator 传递给 Collections.sort 或 Arrays.sort 。
// int compare(Object o1, Object o2);
// @return o1小于、等于或大于o2,分别返回负整数、零或正整数。
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class node{
int x, y;
}
class mycmp implements Comparator<node>{
public int compare(node o1, node o2) {
if(o1.x == o2.x)
return o1.y-o2.y; //按照 y 值从小到大排序
else
return o1.x-o2.x;
}
}
public class Main {
static int maxn = 105;
static node[] a = new node[maxn];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
while(sc.hasNext())
{
n = sc.nextInt();
for(int i = 0; i < n; i++)
{
a[i] = new node(); //类对象必须初始化 分配内存空间
a[i].x = sc.nextInt();
a[i].y = sc.nextInt();
}
Arrays.sort(a, 0, n, new mycmp());
for(int i = 0; i < n; i++)
System.out.println(a[i].x + " " + a[i].y);
}
}
}
二、Comparable
强行对实现它的每个类的对象进行整体排序,实现此接口的对象列表(和数组)可以通过 Collections.sort 或 Arrays.sort 进行自动排序。
// int compareTo(Object o);
// @return 该对象小于、等于或大于指定对象o,分别返回负整数、零或正整数。
import java.util.Arrays;
import java.util.Scanner;
class node implements Comparable<node>{
int x, y;
public int compareTo(node a) {
if(this.x == a.x)
return this.y - a.y; //按照 y 值从小到大排序
else
return this.x - a.x;
}
}
public class Main {
static int maxn = 105;
static node[] a = new node[maxn];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
while(sc.hasNext())
{
n = sc.nextInt();
for(int i = 0; i < n; i++)
{
a[i] = new node(); //类对象必须初始化 分配内存空间
a[i].x = sc.nextInt();
a[i].y = sc.nextInt();
}
Arrays.sort(a, 0, n);
for(int i = 0; i < n; i++)
System.out.println(a[i].x + " " + a[i].y);
}
}
}
用法示例:
import java.util.*;
class S implements Comparable<S>
{
int x,y;
public S(int x ,int y) {
this.x = x;
this.y = y;
}
public int compareTo(S a)
{
if(this.x-a.x != 0)
return this.x-a.x; //按x升序排序
else return this.y-a.y; //如果x相同,按y升序排序
}
}
public class Test
{
public static void main(String args[])
{
Scanner in=new Scanner (System.in);
int n,i;
n=in.nextInt();
S d[] = new S[10];
for(i=0; i<n; i++)
{
int k1 = in.nextInt();
int k2 = in.nextInt();
d[i] = new S(k1,k2);
}
Arrays.sort(d, 0, n); //排n个数,Arrays.sort(d)则默认排全部
for(i=0; i<n; i++)
System.out.println(d[i].x+" "+d[i].y);
}
}
//输出结果:
3
4 5
2 4
2 3
2 3
2 4
4 5