背景 :
Comparator接口可以实现自定义排序,实现Comparator接口时,要重写compare方法:
int compare(Object o1, Object o2) 返回一个基本类型的整型
如果要按照升序排序,则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
如果要按照降序排序,则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)
import java.util.Arrays;
import java.util.Comparator;
public class test5 {
private static class TestClass{
/*
* 测试用的类
*/
Integer num;
String str;
public TestClass(int num,String str) {
this.num = num;
this.str = str;
}
}
public static void main(String[] args) {
TestClass[] tc = new TestClass[10];
tc[0] = new TestClass(10,"yfdsf");
tc[1] = new TestClass(6,"iodfj");
tc[2] = new TestClass(8,"iodfj");
tc[3] = new TestClass(543,"ab");
tc[4] = new TestClass(0,"bgh");
tc[5] = new TestClass(1,"opfdg");
tc[6] = new TestClass(45,"lofgj");
tc[7] = new TestClass(34,"io");
tc[8] = new TestClass(684,"gfk");
tc[9] = new TestClass(9,"09");
/*
* 调用自定义排序
*/
Arrays.sort(tc,new Comparator<TestClass>() {
/*
* 实现Comparator接口
* 重写compare方法
*/
@Override
public int compare(TestClass a,TestClass b) {
return a.num.compareTo(b.num);
}
});
for(TestClass tc1 : tc) {
System.out.println(tc1.num + " " + tc1.str);
}
}
}
结果: