views:

501

answers:

5
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")?

+5  A: 

Since BeanComparator isn't generic, you'll just have to suppress.

UPDATE: Actually, if it bothers you enough, you could fork the codebase to make it generic, since it's Open Source.

Hank Gay
+4  A: 

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.
Stephen C
"Add a suppress warnings annotation". That should be the last resort, should happen only and only when you're 100% sure it's safe.
Marius Burz
Well yes. But in situations like this you can be 100% sure. And if you make a mistake the worst you'll get is a ClassCastException in an unexpected place.
Stephen C
A: 

Yes, you are supposed to use @SuppressWarnings("unchecked"). There is no reason to think the comparator not using generics can cause a problem in that case.

Sindri Traustason
A: 

You could always switch to using Google Collections.

They support Generics.

Fortyrunner
A: 

The only way to remove the warning would be to change the code of BeanComparator, but even if you could, unless you made it a specific wrapper that understands your particular type, the concept wouldn't work well. The class operates on any object by reflection which may or may not have the method. It is inherently not typesafe.

The simplest way around the warning is to implement your own comparator:

 public class QuestionComparator extends Comparator<Question> {
      private BeanComparator peer = new BeanComparator("questionId");

      public int compare(Question o1, Question o2) {
             return peer.compare(o1, o2);
      }
 }

You could also implement equals if it matters, and call the BeanComparator equals method like this:

   public boolean equals(Object o) {
       //boiler plate code here to ensure o is an instance of Question and not null
       return ((QuestionComparator) o).peer.equals(peer);
   }
Yishai