简体   繁体   English

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

[英]Java Collections.sort return null when sorting list of strings

I am trying to sort a list of strings (that will contain alphanumeric characters as well as punctuation) via Collections.sort : 我正在尝试通过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.");
        }
    }
}

When I run this I get: 当我运行它时,我得到:

toSort size is 1
I am null and sad.

Why null? 为什么要为空?

Collections.sort() returns a void , so your new collection sorted is never initialized. Collections.sort()返回一个void ,因此从未初始化已sorted的新集合。

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

is like 就好像

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

To use correctly the Collections.sort() method you must know you are sorting the same object you put in the method : 要正确使用Collections.sort()方法,您必须知道您正在对放入该方法中的同一对象进行排序

Collections.sort(collectionToBeSorted);

In your case: 在您的情况下:

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