我正在尝试使用类似的接口(interface)对对象的 ArrayList 进行排序:
public class Unit implements Comparable<Unit>{
// attributes
int position;
@Override
public int compareTo(Unit other) {
return Integer.compare(position, other.position);
}
}
现在我使用以下方法对 ArrayList 进行排序:
List<Unit> units = getAllUnits();
Collections.sort(units);
上面将从位置0
开始对所有单位进行排序,但我希望它从位置1
开始,因为位置
的默认值是零
。
如何修改 compareTo
方法?
最佳答案
(使用您评论中的信息,不会有负数,)您应该能够使用此:
public int compareTo(Unit other) {
if (position != other.position) {
if (position == 0) {
return 1;
} else if (other.position == 0) {
return -1;
}
return Integer.compare(position, other.position);
} else {
return 0;
}
}
更新:它也适用于负数,示例输出:[-1, 1, 2, 0, 0]
关于Java - 修改compareTo方法以从1开始对整数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657262/