ArrayList的排序 [英] Sorting of ArrayList

查看:34
本文介绍了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.

现在我想根据排名的升序对这个数组列表进行排序.此数组列表中已设置等级值.

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

我如何对数组列表进行排序,哪个有很多类型的值......?

谢谢大家....

推荐答案

使它们都成为一个类型的对象.要么设计一个通用的基类,要么设计一个Interface

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

然后

使用Comparator来整理它们

例如.

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

假设arraylist中的所有对象现在都是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())
}
});

<小时>

或者使用反射 hack ,不可取

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天全站免登陆