排序与多个对象的ArrayList [英] Sort an arrayList with multiple objects

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

问题描述

我在动物取值如下列表:

 的ArrayList<动物>动物=新的ArrayList<动物>();
        animals.add(新的动物(1,animal1,50,10维耶2016年,辄,4,真实));
        animals.add(新的动物(2,animal2,50,10维耶2016年,辄,4,真实));
        animals.add(新的动物(3,animal3,50,10维耶2016年,辄,4,真实));
        animals.add(新动物(4,animal4,50,10维耶2016年,辄,4,真实));
        animals.add(新的动物(5,animal5,50,10维耶2016年,辄,4,真实));

我想通过自己的ID进行排序在的ArrayList 我的动物名单。从我所看到的我必须使用一个比较。

这是我创建至今...

 公共类ComparatorAnimal实现比较<动物> {    公众诠释比较(动物animals.get(0),动物animals.get(1){
        返回animals.get(0).idAnimal - animals.get(1).idAnimal;
    }


解决方案

 公共类ComparatorAnimal实现比较<动物> {公众诠释比较(动物animals.get(0),动物animals.get(1){
    返回animals.get(0).idAnimal - animals.get(1).idAnimal;
}

方法签名是错误的:你是不是比较动物,但两个动物对象的两个列表。
那么你比较两个ID,你并不需要减去它。只要使用同样的方法从Integer类。

改变你的方法是这样的:

 公共类ComparatorAnimal实现比较<动物> {公众诠释比较(动物O1,O2动物){
    返回Integer.compare(o1.idAnimal,o2.idAnimal);
}

现在,你必须使用一个分类收集(如树形图,而不是ArrayList中)或调用 Col​​lections.sort(yourList,yourComparator)

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

解决方案

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)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆