【发布时间】:2018-07-17 11:14:38
【问题描述】:
我知道这类问题已经被问过数百万次,甚至数十亿次,但我还没有找到答案:)
这个compare() 方法没有Long、Double、Float、...,它只有Date、boolean 和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;
}
});
MiniUser.class
public class MiniUser implements Serializable {
String id;
String name;
Date lastMatchDate;
boolean showCompleteName;
//getters, setters
}
checkMatchConditions根据一些计算返回布尔值
【问题讨论】:
-
你认为你为什么需要
Boolean.valueOf(resComing)等?他们会立即被resComing拆箱。 -
user在你的 Comperator 中定义在哪里? -
这显然违反了约定,因为它在与自身比较时不会返回 0(如果
resComing和resExists都是 false)。 -
注意:
if(Boolean.valueOf(resComing) && Boolean.valueOf(resExists))与if(resComing && resExists)相同
标签: java sorting collections comparator code-contracts