I made a list of Animal
s 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;
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With