gpt4 book ai didi

java - 使用 Collections.sort 排序列表时出错

转载 作者:行者123 更新时间:2023-11-29 06:46:23 27 4
gpt4 key购买 nike

当我尝试通过执行 Collections.sort(list2) 对列表进行排序时,出现了 NullPointerException

列表包含以下字符串

[BOOTH 4, ENP ROOM, BOOTH 6, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 10, BOOTH 7, BOOTH 3, BOOTH 1, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 1, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 10, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]

我需要为此列表使用比较器吗?

最佳答案

您可以使用可以处理空值的比较器。例如

private static final class NullsFirstComparator implements Comparator<String> {
public int compare(String lhs, String rhs) {
if (lhs == rhs)
return 0;
if (lhs == null)
return -1;
if (rhs == null)
return 1;
return lhs.compareTo(rhs);
}
}

这将首先对空值进行排序(它们小于所有值)

关于java - 使用 Collections.sort 排序列表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com