【发布时间】:2012-05-10 04:26:26
【问题描述】:
我的问题是关于如何通过其中一个属性对具有自定义对象的 ArrayList 进行排序,但从自定义条件开始。
让我解释一下,这是我的代码:
public static void sortArrayListByProperty(ArrayList colorList){
Collections.sort(colorList, new Comparator(){
public int compare(Object emp1, Object emp2){
int intValue1 = ((ColorCounter)emp1).getIntColorValue();
int intValue2 = ((ColorCounter)emp2).getIntColorValue();
if(intValue1 < intValue2)
return 1;
else if(intValue1 > intValue2)
return -1;
else
return 0;
}
});
}
这会将我的 ArrayList 从大到小排序。
但我想要的是从我将指定的起始编号对我的 ArrayList 进行排序。
例如,如果 ArrayList 包含
5 3 9 1 14
假设我希望数字从 3 开始,那么我需要有
3 5 9 14 1
我希望足够清楚......
有可能吗?
@Joachim Sauer
谢谢,我稍微修改了你的代码并更改了返回值,它成功了!
修改后的代码:
if (cv1 >= threshold && cv2 < threshold) {
return -1;
} else if (cv2 >= threshold && cv2 < threshold) {
return -1;
} else if (cv1 < cv2) {
return 1;
} else if (cv1 > cv2) {
return 1;
} else {
return 0;
}
测试示例:
16777215
16448250
15790320
4013373
按 15790320 排序:
15790320
16448250
16777215
4013373
【问题讨论】:
-
许多解决方案,但我建议您使用简单的模式,例如混合过滤器和排序或混合过滤器和排序和合并?
-
为什么 1 会大于 14?每个小于 3 的数都会大于任何大于 3 的数吗?两个小于 3 的数字如何相互比较?
-
如果在此列表中添加 2、8、10 会发生什么?这些输入之间的逻辑差异是什么?我认为您最好将它们添加到所需的位置
标签: java sorting arraylist conditional-statements