Use Collections.sort(List<T> list, Comparator<? super T> c) and pass a custom comparator for your DAO objects.
This is much simpler if all the items in the list have a common supertype, which provides a method for getting the ranking of an item. Assuming you have such an interface, call it RankProvider , the comparator might look like this:
public class Comparator<RankProvider> { @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 above example assumes that the ranking of an element is either a java primitive (e.g. int ), or a string, or, in other words, is Comparable (directly or after the incoming)
Unless you have a common superclass or interface, the comparison is not trivial. You either need to know all the possible types, or process them for each of them, 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 can be done if you do not have the ability to reorganize your DAOs to implement a common interface.
Andreas_D Mar 15 '11 at 8:32 2011-03-15 08:32
source share