繁体   English   中英

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

[英]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()返回一个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.");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM