Comparator和Comparable在排序中的应用
当需要排序的集合或数组不是单纯的数字型时,通常可以使用Comparator或Comparable,以简单的方式实现对象排序或自定义排序。
一、Comparator
强行对某个对象collection进行整体排序的比较函数,可以将Comparator传递给Collections.sort或Arrays.sort。
接口方法:
/**
* @return o1小于、等于或大于o2,分别返回负整数、零或正整数。
*/
当需要排序的集合或数组不是单纯的数字型时,通常可以使用Comparator或Comparable,以简单的方式实现对象排序或自定义排序。
一、Comparator
强行对某个对象collection进行整体排序的比较函数,可以将Comparator传递给Collections.sort或Arrays.sort。
接口方法:
/**
* @return o1小于、等于或大于o2,分别返回负整数、零或正整数。
*/
int compare(Object o1, Object 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;
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进行自动排序。
接口方法:
/**
* @return 该对象小于、等于或大于指定对象o,分别返回负整数、零或正整数。
*/
int compareTo(Object 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;
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);
}
}
}