Forum Stats

  • 3,760,204 Users
  • 2,251,664 Discussions


Sorting method

843793 Member Posts: 41,732 Green Ribbon
edited Apr 25, 2010 1:31AM in Generics
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?


  • DrClap
    DrClap Member Posts: 25,479
    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.)
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    Ok, thanks for the very clear explanation.
This discussion has been closed.