4

I made a list of Animals as follows :

        ArrayList<Animal> animals = new ArrayList<Animal>();
        animals.add(new Animal(1, "animal1", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(2, "animal2", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(3, "animal3", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(4, "animal4", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(5, "animal5", 50, "10 Janvier 2016", "Noir", 4, true));

I want to sort my list of animals in ArrayList by their ID. From what i've seen i have to use a comparator.

This is what i created so far...

public class ComparatorAnimal implements Comparator<Animal> {

    public int compare(Animal animals.get(0), Animal animals.get(1) {
        return animals.get(0).idAnimal - animals.get(1).idAnimal;
    }
2
  • The Comperator interface actually tells you the signature of the method that you do have to implement. If you don´t have a method with this signature inside your class then it would not compile, which i guess is the case right now. Well and you can´t name your variables like animals.get(0) Commented Jan 11, 2016 at 14:37
  • This type of questions have been asked and answered multiple times. It's a duplicate question. Commented Jan 11, 2016 at 15:19

2 Answers 2

8
public class ComparatorAnimal implements Comparator<Animal> {

public int compare(Animal animals.get(0), Animal animals.get(1) {
    return animals.get(0).idAnimal - animals.get(1).idAnimal;
}

The method signature is wrong: you are not comparing two lists of Animal but two Animal object. Then you are comparing two id, you don't need to subtract it. Just use the same method from the Integer class.

Change your method like this:

public class ComparatorAnimal implements Comparator<Animal> {

public int compare(Animal o1, Animal o2) {
    return Integer.compare(o1.idAnimal, o2.idAnimal);
}

Now you have to use a sorted collection (like TreeMap instead of ArrayList) or invoke Collections.sort(yourList, yourComparator)

Sign up to request clarification or add additional context in comments.

Comments

2

Change

public int compare(Animal animals.get(0), Animal animals.get(1) {
    return animals.get(0).idAnimal - animals.get(1).idAnimal;
}

to

public int compare(Animal animal1, Animal animal2 {
    if(animal1.idAnimal > animal2.idAnimal)
        return 1;
    else if(animal1.idAnimal < animal2.idAnimal)
        return -1;

    return 0;
}

& then use

Collections.sort(animals, new ComparatorAnimal());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.