Java Collections.sort 对字符串列表进行排序时返回 null

sme*_*eeb -1 java sorting collections list

我正在尝试通过以下方式对字符串列表(将包含字母数字字符以及标点符号)进行排序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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到:

toSort size is 1
I am null and sad.
Run Code Online (Sandbox Code Playgroud)

为什么为空?

Jor*_*lla 5

Collections.sort()返回 a void,因此您的新集合sorted永远不会初始化。

List<String> sorted = Collections.sort(toSort);
Run Code Online (Sandbox Code Playgroud)

就好像

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

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

Collections.sort(collectionToBeSorted);
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)