[英]Is this how to implement ascending sort when the comparator sorts descending?
[英]How to use Comparator<Object> for Ascending, Descending without sorting
我试图得到一个答案,但是有关比较器的每个问题都涉及到排序。
我试图将Comparator与dog.getAge()
值一起使用
我的班级看起来像
public final class Dog implements Comparator<Dog>{
...
@Override
public int compare(Dog o1, Dog o2) {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o2.getAge() > o1.getAge()) {
return 2;
}
return 0;
}
}
在主要活动中,我尝试比较狗,但我认为问题是Iam不知道如何结束这种方法,
我也收到一个错误: Fatal Exception thrown on Scheduler.
我正在尝试从api获取狗。
所以这是我在MainActivity中的方法
private List<Dog> dogsArray = new ArrayList<>();
private void checkAscendingOrDescendingDogsAge() {
Dog dog= new Dog();
for (int i = 0; i < dogsArray.size(); i++) {
dog.compare(dogsArray.get(i), dogsArray.get(i + 1));
}
}
无论您的预期用途是什么; 这里:
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o2.getAge() > o1.getAge()) {
return 2;
}
是不正确的。 这个想法是compareTo()
返回负的,等于零的正结果。 没有必要自己决定要更改该方法的约定为:1对于o1早于o2; 大于o1的o2为2。 该接口和该方法具有明确定义的合同,您只需遵守该合同即可。 除非您的目标是故意误导读者。 但是请放心,那会很快咬你。
假设getAge()
返回int,则只需将其替换为:
return Integer.compare(o1.getAge(), o2.getAge())
然后, 诀窍是定义其他方法,例如:
public boolean isOlder(Dog other) {
return compareTo(this, other) > 0;
例如。
您可以这样使用:
Dog buddy = new Dog(...
Dog sparky = new Dog(...
if (buddy.isOlder(sparky)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.