Android按属性对arraylist进行排序
我想ArrayList
按属性排序。这是我的代码…
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
在另一个活动中。但是我不知道该怎么做。有人知道吗?
回答:
您需要实现Comparator
,例如:
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按属性对arraylist进行排序 的全部内容, 来源链接: utcz.com/qa/425715.html