Sort an array with multiple objects

I made the list Animalas 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 the list of animals in ArrayListby their identifier. From what I saw, I have to use a comparator.

This is what I have 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;
    }
+4
source share
2 answers
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 incorrect: you are not comparing two lists Animal, but two objects Animal. Then you compare two identifiers, you do not need to subtract it. Just use the same method from the Integer class.

Change your method as follows:

public class ComparatorAnimal implements Comparator<Animal> {

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

Now you need to use a sorted collection (e.g. TreeMap instead of ArrayList) or call Collections.sort(yourList, yourComparator)

+9

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

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

    return 0;
}

&

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

Source: https://habr.com/ru/post/1623772/


All Articles