【发布时间】:2014-06-01 15:05:54
【问题描述】:
我有一个对象 Collection,有 5 个字段:
id;
entityType;
entityId;
brandId;
productId;
为了对Collection 中的ArrayList 进行排序,我编写了以下Comparaor。
Comparator<Collection> collectionComparator = new Comparator<Collection>() {
@Override
public int compare(Collection collection1, Collection collection2) {
if(collection1.getId().equals(collection2.getId())) {
if(collection1.getEntityType().equals(collection2.getEntityType())) {
if(collection1.getEntityId().equals(collection2.getEntityId())) {
if(collection1.getBrandId().equals(collection2.getBrandId())) {
return collection1.getProductId().compareTo(collection2.getProductId());
} else {
return collection1.getBrandId().compareTo(collection2.getBrandId());
}
} else {
return collection1.getEntityId().compareTo(collection2.getEntityId());
}
} else {
return collection1.getEntityType().compareTo(collection2.getEntityType());
}
}
return collection1.getId().compareTo(collection2.getId());
}
};
这是在具有多个要比较的字段的对象上实现Comparator 的正确方法吗?
【问题讨论】:
-
“对”?你在问什么?为什么不只测试您的代码?
-
这是错误的,因为 Collection 上没有 getId,除非你自己实现了它,这可能也是不必要的
-
这个问题似乎跑题了,因为用户要求我们写测试用例,用户懒得自己写。
-
它不是 Java 集合,而是时尚的集合?
-
@djechlin 很抱歉,但我必须说,您的回答对我没有帮助。我以错误的方式问了这个问题。我已经编辑过了。在说“用户要求我们写测试用例之前,用户懒得自己写”。您应该查看该用户的个人资料,看看他是否懒惰。
标签: java sorting object comparator