Arrays.sort()和Collections.sort()都提供自然升序,但是如果想要升序(也可以降序)就需要使用对应的类实现Comparator接口重写compare方法
Arrays.sort(基本类型数组)-------从小到大
Arrays.sort(int[] a, int fromIndex, int toIndex)-------对部分数组从小到大排序
public static
public class Test {
public static void main(String[] args) {
Integer[] arr = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(arr, new MyComparator());
for(int i = 0; i < arr.length; i ++) {
System.out.print(arr[i] );
}
}
}
class MyComparator implements Comparator{
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;//降序:9876543210
//return o2-o1;升序:0123456789
}
}
Collections.sort(List
List lists = new ArrayList();
lists.add("1");
lists.add("6");
lists.add("3");
Collections.sort(List
public class TestA implements Comparator{
private static final long serialVersionUID = -8968350748602548887L;
private String name;
//变量类型必须要为int的封装类型,因为只有是封装类型才可以调用Integer的方法
private Integer order;
public String getName() {
return name;
}
….
@Override
public int compare(TestA o1, TestA o2) {
//升序
return o1.getOrder().compareTo(o2.getOrder());
}
}
public class Test {
private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
List listA = new ArrayList();
//TestA 即是上面类
TestA a1 = new TestA();
a1.setName("张三");
a1.setOrder(1);
listA.add(a1);
TestA a5 = new TestA();
a5.setName("王屋");
a5.setOrder(5);
listA.add(a5);
TestA a3 = new TestA();
a3.setName("刘六");
a3.setOrder(3);
listA.add(a3);
Collection.sort(listA,new TestA());
//也可以这么干,TestA里不实现Comparator接口排序,在真正调用sort时再排序,如下:
Collections.sort(listA, new Comparator() {
@Override
public int compare(TestA o1, TestA o2) {
//升序
return o1.getOrder().compareTo(o2.getOrder());
}
});
//ArrayList自身在JDK1.8也增加了sort方法
listA.sort(new Comparator() {
public int compare(TestA o1, TestA o2) {
//升序
return o1.getOrder().compareTo(o2.getOrder());
}
}