0

I would like to sort a List/Set of Class given a personnal order (like A.class < B.class < C.class for instance). But Class doesn't implements Comparable, and I obviously can't customize the class Class without rewriting the whole Java language, so what are my options?

Thanks a lot !

Aleksandr Podkutin
  • 2,532
  • 1
  • 20
  • 31
Sharcoux
  • 5,546
  • 7
  • 45
  • 78

1 Answers1

0

You can use a custom Comparator. Just implement that interface and you can use it with Collections.sort() and sorted sets (pass the comparator as constructor)

Comparator<Class<?>> c=new Comparator<Class<?>>{
  @Override
  int compare(Class<?> a, Class<?> b) { 
     // your comparison logic 
  }
};

List<Class<?>> list= ...
Collections.sort(list, c);

Set<Class<?>> set=new TreeSet<>(c);
ruediste
  • 2,434
  • 1
  • 21
  • 30
  • Ok. Got it! I knew only about the other way of sorting. Thanks a lot. I try that right now – Sharcoux Jun 15 '14 at 13:10
  • Damn, marked as dupe before answering. But try comparing by the class' simple name. – Rogue Jun 15 '14 at 13:11
  • Actually I need to compare with instanceof. Otherwise, I wouldn't bother carrying a List. I would just use a List. But thanks. – Sharcoux Jun 15 '14 at 13:16