Aod Ren
Aod Ren

Reputation: 679

Sort an arrayList with multiple objects

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

Upvotes: 4

Views: 1050

Answers (2)

Gianni B.
Gianni B.

Reputation: 2731

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)

Upvotes: 9

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

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());

Upvotes: 1

Related Questions