【问题标题】:Java Collections.sort return null when sorting list of stringsJava Collections.sort 在对字符串列表进行排序时返回 null
【发布时间】:2015-05-11 11:09:12
【问题描述】:

我正在尝试通过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...
  • Collections.sort() 的返回类型为 void。它修改了它传递的List
  • 是的@Thomas - 我的实际代码在 Groovy 中,但我将其转换为 Java 以加快对问题的回答。似乎 Groovy 的动态特性掩盖了 Java 会立即暴露为编译器错误的内容。

标签: java list sorting collections


【解决方案1】:

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.");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 2018-05-10
    • 2012-04-22
    • 2021-02-21
    • 2015-03-26
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多