我知道这种问题已经被问过数百万次(如果不是数十亿次),但我还找不到答案:)
This compare()
方法没有Long
, Double
, Float
, ..., 它只有Date
, boolean
, and Null
检查员,但是它告诉我contract violation error
,有人可以帮忙吗?
Collections.sort(users, new Comparator<MiniUser>() {
@Override
public int compare(MiniUser u1, MiniUser u2) {
boolean resComing = checkMatchConditions(u1,user);
boolean resExists = checkMatchConditions(u2,user);
if(Boolean.valueOf(resComing) && Boolean.valueOf(resExists)) {
if(u1.getLastMatchDate() == null){
return -1;
}else if(u2.getLastMatchDate() ==null ){
return 1;
}else if (u1.getLastMatchDate().toInstant().isBefore(u2.getLastMatchDate().toInstant())){
return -1;
}else {
return 1;
}
}
else if (Boolean.valueOf(resComing)) {
return -1;
}
return 1;
}
});
迷你用户类
public class MiniUser implements Serializable {
String id;
String name;
Date lastMatchDate;
boolean showCompleteName;
//getters, setters
}
checkMatchConditions
根据一些计算返回布尔值
您应该首先阅读Comparator.compare() 的 JavaDoc https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-了解“合同”是什么:
实现者必须确保 sgn(compare(x, y)) == -sgn(compare(y,
x)) 对于所有 x 和 y。
一般来说,它表示如果“x 大于 y,则 y 必须小于 x”。听起来很明显,但在您的比较器中情况并非如此:
- 在你的情况下,当两个用户有
checkMatchConditions
false
, 在这种情况下compare(u1, u2)
and compare(u2, u1)
两者都返回 1。因此,在某些情况下u1
大于u2
, and u2
大于u1
,这是一种违规行为。
- 同样,如果两个用户都有
checkMatchConditions
true
,以及他们的lastMatchDates
都是null
,他们也会违反合同。
- 此外,因为您手动尝试将日期与
isBefore
,当两个用户有两种情况时,您也会返回 -1checkMatchConditions
true
和他们的lastMatchDates
两者相等。
为了解决这个问题,您应该首先添加自然语言描述,说明您希望如何对用户进行排序。然后你就可以计算出比较器逻辑。
该错误与以下内容无关Boolean.valueOf()
顺便一提。
现在您已经解释了如何订购,请看一下这个比较器:
public int compare(MiniUser u1, MiniUser u2)
{
// order by match
boolean u1Matches = checkMatchConditions(u1, user);
boolean u2Matches = checkMatchConditions(u2, user);
if (u1Matches != u2Matches)
{
// put matching ones first
return u1Matches ? -1 : 1;
}
else if (u1Matches)
{
// order by dates
boolean u1HasDate = u1.getLastMatchDate() != null;
boolean u2HasDate = u2.getLastMatchDate() != null;
if (u1HasDate != u2HasDate)
{
// put the ones without date first
return u1HasDate ? 1 : -1;
}
else if (u1HasDate)
{
// order chronologically
return u1.getLastMatchDate().compareTo(u2.getLastMatchDate());
}
else
{
// no dates, no order possible
return 0;
}
}
else
{
// both don't match, no order possible
return 0;
}
}
如果我正确理解您的要求,这应该对您的元素施加一致的顺序。注意我的使用方式Date
's compareTo
日期订购而不是自己做,以及我如何返回0
如果它们在顺序上“相等”而不是“随机”返回1
or -1
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)