简体   繁体   中英

How to use Comparator<Object> for Ascending, Descending without sorting

I try to get an answer but every question about Comparators deals with sorting.

Im trying to use a Comparator with values from dog.getAge()

My class look like

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;
    }
}

And in main activity i try compare the dogs, but i think the problem is Iam dont know how to end this method,

Also i got an error: Fatal Exception thrown on Scheduler.

I am trying to get dogs from api.

So here is my method in 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));
        }
    }

No matter what your intended use is; this here:

if (o1.getAge() > o2.getAge()) {
  return 1;
} else if (o2.getAge() > o1.getAge()) {
  return 2;
}

is incorrect. The idea is that compareTo() returns negative, equal zero , positive results. There is no point in deciding for yourself that you want to change the contract of that method to say: 1 for o1 older than o2; and 2 for o2 older than o1. This interface, and that method have a well defined contract, and you simply stick to that. Unless your goal is to mislead your readers on purpose. But be assured, that will bite back on you quickly.

Assuming that getAge() returns, say int, you simply replace that with:

 return Integer.compare(o1.getAge(), o2.getAge())

And then the trick is to define additional methods such as:

public boolean isOlder(Dog other) {
  return compareTo(this, other) > 0;

for example.

And you use that like:

Dog buddy = new Dog(...
Dog sparky = new Dog(...

if (buddy.isOlder(sparky)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM