Sorting of ArrayList

后端 未结 5 2263
渐次进展
渐次进展 2020-12-10 22:24

I have one array list

ArrayList itemListWithRank = ItemListDAO.getItemList();

and in arraylist itemListWithRank there are lot

5条回答
  •  一生所求
    2020-12-10 23:04

    Use Collections.sort(List list, Comparator c) and pass a custom comparator for your DAO objects.

    It's by far easier if all of your list items share a common supertype that provides a method to get the item rank. Assuming you have such an interface, let's call it RankProvider, the comparator could look like:

    public class Comparator {
      @Override
      public int compare(RankProvider o1, RankProvider o2) {
        return o1.getItemRank().compareTo(o2.getItemRank());
      }
    }
    

    Pass an instance of this comparator or define an anonymous class.

    Note - the example give above assumes, that the item rank is either a java primitive (like int) or a String or, in other words, is a Comparable (directly or after inboxing)


    If you don't have a common superclass or interface, then comparing is less trivial. You'll either have to know all possible types and handle them each by each or you know that all types have the same method (name) and you can reflect the rank. One example for a comparator that compares known but random types:

    public class Comparator {  // no generics this time
      @Override
      public int compare(Object o1, Object o2) {
         Object[] comparables = new Object{o1, o2};
         int[] ranks = new int[2];
    
         for (int i = 0; i < 2; i++) {
           if (comparables[i] instanceof MyType1) {
             ranks[i] = ((MyType1) comparables[i]).getRank(); // rank getter for MyType1 type
             continue;
           }
    
           if (comparables[i] instanceof MyType2) {
             ranks[i] = ((MyType2) comparables[i]).getRank(); // rank getter for MyType2 type
             continue;
           }
    
           // ...
         }
         return ranks[0] - ranks[1];  // ascending order
      }
    }
    

    This could be done if you have no chance to refactor your DAOs to implement a shared interface.

提交回复
热议问题