ArrayList的排序 [英] Sorting of ArrayList

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

问题描述

我有一个数组列表

ArrayList itemListWithRank = ItemListDAO.getItemList();

和ArrayList中 itemListWithRank 有很多类型对象的值。这些都是不同的。而从他们的一个值是项排名也设置与数组列表。

and in arraylist itemListWithRank there are lots of type of objects values those all are different. And one value from them is item rank that also set with that array list.

现在我想根据accending排名顺序排序这个数组列表。排名值在这个数组列表中已设置。

Now i want to sort this array list based on accending order of rank. Rank value is already set in this array list.

如何排序的ArrayList哪一个有很多类型的值的....?

感谢所有....

推荐答案

请他们一个类型的所有对象。无论是设计一个共同的基类或接口

Make them all object of a type. either design a common Base class or an Interface

然后

使用比较,将它们整理

例如

public class SortableFields{
  protected long rank;
  //accessors methods
}

假设在数组列表中的所有对象都SortableFields现在

assumed that all the objects in arraylist are SortableFields now

现在

Collections.sort(list,new Comparator(){
public int compareTo(Object ob1,Object ob){
  return ((SortableFild)ob1.getRank())-((SortableFild)ob2.getRank())
}
});


或者使用反射劈,的不是preferable

Collections.sort(list,new Comparator(){
public int compareTo(Object ob1,Object ob){
     UtilClass.getRank(ob1)-UtilClass.getRank(ob);      
}
});

在您的UtilClass

In your UtilClass

public int getRank(Object ob){

      Class cl=ob1.getClass();
      Method mthd=cl.getMethod("getRank");
      Integer output=(Integer)mthd1.invoke(ob);
      return output;

}

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

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