Java Collections.sort return 排序字符串列表时为空

Java Collections.sort return null when sorting list of strings

我正在尝试通过 Collections.sort:

对字符串列表(将包含字母数字字符和标点符号)进行排序
public class SorterDriver {
    public static void main(String[] args) {
        List<String> toSort = new ArrayList<String>();

        toSort.add("fizzbuzz");
        System.out.println("toSort size is " + toSort.size());

        List<String> sorted = Collections.sort(toSort);
        if(sorted == null) {
            System.out.println("I am null and sad.");
        } else {
            System.out.println("I am not null.");
        }
    }
}

当我 运行 我得到:

toSort size is 1
I am null and sad.

为什么为空?

Collections.sort() returns a void,所以你的新集合 sorted 永远不会被初始化。

List<String> sorted = Collections.sort(toSort);

就像

List<String> sorted = null;
Collections.sort(toSort);    
//                 ^------------> toSort is being sorted!

要正确使用 Collections.sort() 方法,您必须知道您正在对放入方法中的同一对象进行排序:

Collections.sort(collectionToBeSorted);

你的情况:

public class SorterDriver {
    public static void main(String[] args) {
        List<String> toSort = new ArrayList<String>();

        toSort.add("fizzbuzz");
        System.out.println("toSort size is " + toSort.size());

        Collections.sort(toSort);
        if(toSort == null) {
            System.out.println("I am null and sad.");
        } else {
            System.out.println("I am not null.");
        }
    }
}