java中Comparator接口的用法

时间:2021-06-24 02:51:46
/**
* 功能:通过对一个整形数组进行排序,来了解Comparator用法
*
* @author wangchangshuai0010 山东科技大学 2013年2月7日 0:05
*/
package test;

import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Test
{
private class MyComparator implements Comparator<Integer>
{
@Override
public int compare(Integer o1, Integer o2)
{
if (o1 > o2)
{
return 1;
}
else if (o1 < o2)
{
return -1;
}
else
{
return 0;
}
}
}

public static void main(String[] args)
{
Test main = new Test();
MyComparator mComparator = main.new MyComparator();
Scanner cin = new Scanner(new BufferedInputStream(System.in));
System.out.println("请输入数组的长度:");
int count = cin.nextInt();
Integer A[] = new Integer[count];
System.out.println("请依次输入这 " + count + " 个数:");
for (int i = 0; i < A.length; i++)
{
A[i] = cin.nextInt();
}
Arrays.sort(A, mComparator);
System.out.println("排序结果如下:");
for (int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
}
}