sort-compareTo

package com.sl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {
/**
* 关注下 Arrays.sort() 方法实现
* @param names
*/
private void sortUsingjava7(List names){

    //1.Collections 比较器 Comparator
    Collections.sort(names, new Comparator() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
    //2.默认从小到大排序
    Collections.sort(names);
    //3.list比较器
    names.sort(new Comparator() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
}

private void sortUsingjava8(List names){
    //java 8
    Collections.sort(names,(s1,s2) -> s1.compareTo(s2));
}
public static void main(String[] args) {
    String str1 = "1111";
    String str2 =  "1";
    System.out.println(str1.compareTo(str2));

    str2 =  "2";
    System.out.println(str1.compareTo(str2));

    str1 = null;
    System.out.println(str1.compareTo(str2));

    Integer inta = 1111;
    Integer intb = 1;
    System.out.println(inta.compareTo(intb));

    List names1 = new ArrayList<>();
    names1.add("Google ");
    names1.add("Runoob ");
    names1.add("Taobao ");
    names1.add("Baidu ");
    names1.add("Sina ");

    List names2 = new ArrayList<>();
    names2.add("Google ");
    names2.add("Runoob ");
    names2.add("Taobao ");
    names2.add("Baidu ");
    names2.add("Sina ");

    Test test = new Test();
    test.sortUsingjava7(names1);
    System.out.println(names1);

    names2 = null;
    test.sortUsingjava8(names2);
    System.out.println(names2);

}

}
我看了部分compareTo的源码,但是有一些小困惑
sort-compareTo_第1张图片
在while里面为什么要这么设计呢?为什么是从后往前便利返回结果呢?

你可能感兴趣的:(java8)