Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
311 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

and then sort it like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...