我正在尝试整理我的习惯NewsAdapter
by a Date
的财产Articles_Map
对象,并且我注意到,在数据集较大的情况下,我的应用程序会崩溃java.lang.IllegalArgumentException: Comparison method violates its general contract!
error.
我不确定该错误是否是由于以下原因发生的int
溢出,或者是否确实与合约的传递性相关。特别是对于后者,我不知道如何解决它,因为据我所知,我已经处理了 3 种可能的结果(小于 0、0、大于 0)。
public class NewsAdapter extends ArrayAdapter<Articles_Map> {
Context mContext;
public NewsAdapter(Context c, int resource) {
super(c, resource);
this.mContext = c;
}
protected void doAdd(Articles_Map another) {
super.add(another);
}
public void addAll(List<Articles_Map> others) {
for (Articles_Map a : others) {
this.doAdd(a);
}
this.sort(byPublishedAtComparator);
}
private static final Comparator<Articles_Map> byPublishedAtComparator =
new Comparator<Articles_Map>() {
@Override
public int compare(Articles_Map o1, Articles_Map o2) {
// needs further testing in case of nulls
if (o1.publishedAt == null || o2.publishedAt == null) {
return 0;
}
return o1.publishedAt.compareTo(o2.publishedAt);
}
};
}
Your Comparator
违反传递性要求,如果publishedAt
is null
.
假设您有三个实例Articles_Map
:
- a - 值为
publishedAt
- b - 与
publishedAt
== null
- c - 值为
publishedtAt
大于a
s value
现在,如果您使用以下命令调用比较器a
and b
或与b
and c
,比较器返回0
对于这两个电话。
为了满足传递性规则,您的比较器还必须返回0
如果它被调用a
and c
。但自从上场publishedAt
is not null
对于两个对象,它将返回一个小于0
如果按照描述准备。
要解决此问题,您的比较器不得返回0
如果只有其中之一o1.publishedAt
and o2.publishedAt
is null
.
例如:
private static final Comparator<Articles_Map> byPublishedAtComparator =
new Comparator<Articles_Map>() {
@Override
public int compare(Articles_Map o1, Articles_Map o2) {
// needs further testing in case of nulls
if (o1.publishedAt == null) {
return (o2.publishedAt == null) ? 0 : -1;
} else if (o2.publishedAt == null) {
return 1;
}
return o1.publishedAt.compareTo(o2.publishedAt);
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)