2 Replies Latest reply on Apr 25, 2010 5:31 AM by 843793

    Sorting method

      I need a method that would be used for sorting list of POJOs. In the invocation I pass the list of objects to sort and a field name that would be used in a comparator. I need such method cause it'll be used for some classes that have nothing in common and sorting will be based on different fields. Objects are pulled out from database and I know that the sorting process should be carried on db's side but the lists aren't very long and it can be sorted in Java. Here's my code:
      public <T> List<T> sortList(List<T> l, final String s) {
                Collections.sort(l, new Comparator<T>() {
                     public int compare(T o1, T o2) {
                          try {
                               Field f1 = o1.getClass().getDeclaredField(s);
                               Field f2 = o2.getClass().getDeclaredField(s);
                               Object v1 = f1.get(o1);
                               Object v2 = f2.get(o2);
                               return ((Comparable) v1).compareTo((Comparable) v2);
                          } catch (Exception e) {
                               return -1;
                return l;
      And the question is to how to (if it's possible) parametrize the following line:
      return ((Comparable) v1).compareTo((Comparable) v2);
      that the warning won't be displayed (i know about annotations)?
      And maybe there's better idea for implementing such method?
        • 1. Re: Sorting method
          You would have to persuade the getDeclaredField() method to return something which implements Comparable. Which of course it can't, since there's no guarantee that the string you pass is the name of a field which implements Comparable. So you're stuck casting. Then if you pass the name of a field whose type doesn't implement Comparable, you'll get a ClassCastException.

          (The fact that ClassCastException is possible is a clear indication that you can't use a generic type parameter to avoid explicit casting in your code.)
          • 2. Re: Sorting method
            Ok, thanks for the very clear explanation.