本文介绍了对具有多个对象的 arrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个 Animal 列表如下:

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

我想按 ID 对 ArrayList 中的动物列表进行排序.据我所知,我必须使用比较器.

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

方法签名错误:您不是在比较两个 Animal 列表,而是比较两个 Animal 对象.然后你比较两个id,你不需要减去它.只需使用 Integer 类中的相同方法即可.

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.

像这样改变你的方法:

public class ComparatorAnimal implements Comparator<Animal> {

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

现在您必须使用排序集合(如 TreeMap 而不是 ArrayList)或调用 Collections.sort(yourList, yourComparator)

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

这篇关于对具有多个对象的 arrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:39