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 have one array list

ArrayList itemListWithRank = ItemListDAO.getItemList();

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.

How can i sort arraylist which one have lots of type of values....?

Thanks all....

See Question&Answers more detail:os

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

1 Answer

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

and then

use Comparator to sort them out

For example.

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

assumed that all the objects in arraylist are SortableFields now

Now

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

Or use reflection hack , not preferable

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

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;

}

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

548k questions

547k answers

4 comments

86.3k users

...