gpt4 book ai didi

java - Collections.sort() 方法上的 IllegalArgumentException

转载 作者:行者123 更新时间:2023-12-04 20:49:32 24 4
gpt4 key购买 nike

我有字符串比较器,它被转换为日期。当我将此比较器传递给 Collections.sort() 方法时,我得到 java.lang.IllegalArgumentException: Comparison method violates its general contract!

我看过一些关于这个异常的文章,但是我不太明白为什么会出现这个异常。有什么想法吗?

private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");   

Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
try {
Date first = sdf.parse(o1);
Date second = sdf.parse(o2);
return first.compareTo(second);
} catch (Exception ignored) {
return 0;
}
}
};

最佳答案

如果抛出异常,则返回 0。这意味着无论何时无法解析任何参数,都将被视为相等。想想这个例子:

a = "01/01/2015"
b = "01/01/2016"
c = "xxx"

然后你得到

comparator.compare(a,c) = 0
comparator.compare(b,c) = 0

但是

comparator.compare(a,b) != 0

解决方案:尝试分别解析每个字符串,并在异常情况下使用 null,如下所示:

private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");

Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Date first;
try {
first = sdf.parse(o1);
} catch (Exception ignored) {
first = null;
}
Date second;
try {
second = sdf.parse(o2);
} catch (Exception ignored) {
second = null;
}

if (first == second) {
return 0;
}
if (first == null) {
return 1;
}
if (second == null) {
return -1;
}
return first.compareTo(second);
}
};

关于java - Collections.sort() 方法上的 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31556639/

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