Android 按属性对数组列表进行排序 [英] Android sort arraylist by properties

查看:33
本文介绍了Android 按属性对数组列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按属性对 ArrayList 进行排序.这是我的代码...

I want to sort an ArrayList by a property. This is my code...

public class FishDB{

    public static Object Fish;
    public ArrayList<Fish> list = new ArrayList<Fish>();

    public class Fish{
        String name;
        int length;
        String LatinName;
        //etc. 

        public Vis (String name) {
            this.name = name;
        }
    }

    public FishDB() {
        Fish fish;

        fish = new Fish("Shark");
        fish.length = 200;
        fish.LatinName = "Carcharodon Carcharias";

        fish = new Fish("Rainbow Trout");
        fish.length = 80;
        fish.LatinName = "Oncorhynchus Mykiss";

        //etc.
        }
    }
}

现在我想通过一个属性对这个 ArrayList 进行排序,例如另一个活动中的 latinname.但我不知道该怎么做.有人知道怎么做吗?

Now I want in want to sort this ArrayList by a property e.g the latinname in another activity. But I don't know how to do that. Does anybody know how?

推荐答案

你需要实现一个Comparator,例如:

You need to implement a Comparator, for instance:

public class FishNameComparator implements Comparator<Fish>
{
    public int compare(Fish left, Fish right) {
        return left.name.compareTo(right.name);
    }
}

然后这样排序:

Collections.sort(fishes, new FishNameComparator());

这篇关于Android 按属性对数组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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