Java Collections.sort - help me remove the unchecked warning

emulcahy picture emulcahy · Nov 30, 2009 · Viewed 10.3k times · Source
List<Question> questions = new ArrayList<Question>();
questions.addAll(getAllQuestions()); //returns a set of Questions
Collections.sort(questions, new BeanComparator("questionId")); //org.apache.commons.beanutils.BeanComparator

Under Java 1.5, the above works fine except that the 'new BeanComparator("questionId")' generates an unchecked warning. I do not like warnings. Is there a way I can provide the BeanComparator a type, or do I have to use @SuppressWarnings("unchecked")?

Answer

Stephen C picture Stephen C · Nov 30, 2009

Options are:

  • Change BeanComparator to implement Comparator<Question>. This is not a real option here, given it is a well-known external library class. People ain't going to let you do it.
  • Fork and modify BeanComparator as above, giving it a different FQN.
  • Wrap the existing BeanComparator with a class that implements Comparator<Question>.
  • Change the type of questions to List<?>.
  • Add a suppress warnings annotation.