Collections.sort()方法上的IllegalArgumentException [英] IllegalArgumentException on Collections.sort() method
问题描述
我有用于字符串的比较器,这些字符串已转换为日期。当我将此比较器传递给Collections.sort()方法时,我得到 java.lang.IllegalArgumentException:比较方法违反了它的常规约定!。
I have comparator for strings, which are converted to date. When I pass this comparator to Collections.sort() method I get java.lang.IllegalArgumentException: Comparison method violates its general contract!.
我已经阅读了一些有关此异常的文章,但是我真的不明白为什么会出现此异常。知道吗?
I have read some articles about this exception, but I don't really understand why this exception appears. Any idea ?
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。这意味着无论何时无法解析任何参数,都将被视为相等。考虑以下示例:
In case an exception is thrown, you return 0. That means whenever any of the arguments cannot be parsed, both are considered equal. Think of this example:
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
像这样:
Solution: Try parsing each of the Strings separately, and on exception use null
like this:
私有SimpleDateFormat sdf = new SimpleDateFormat( dd / MM / yyyy HH:mm);
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);
}
};
这篇关于Collections.sort()方法上的IllegalArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!