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

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

java - Sorting of ArrayList

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

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

1 Answer

0 votes
by (71.8m points)

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;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...