简体   繁体   English

使用多个对象对arrayList进行排序

[英]Sort an arrayList with multiple objects

I made a list of Animal s as follows : 我制作了Animal名单如下:

        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. 我想按照他们的ID对ArrayList中的动物列表进行排序。 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. 方法签名是错误的:您不是比较两个Animal列表而是两个Animal对象。 Then you are comparing two id, you don't need to subtract it. 然后你比较两个id,你不需要减去它。 Just use the same method from the Integer class. 只需使用Integer类中的相同方法即可。

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) 现在你必须使用一个有序集合(比如TreeMap而不是ArrayList)或者调用Collections.sort(yourList, yourComparator)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM