Java Collections.sort – 帮我删除未经检查的警告

List questions = new ArrayList(); questions.addAll(getAllQuestions()); //returns a set of Questions Collections.sort(questions, new BeanComparator("questionId")); //org.apache.commons.beanutils.BeanComparator 

在Java 1.5下,上述工作正常,只是’new BeanComparator(“questionId”)’生成一个未经检查的警告。 我不喜欢警告。 有没有办法可以为BeanComparator提供类型,还是必须使用@SuppressWarnings("unchecked")

选项包括:

  • 更改BeanComparator以实现Comparator 。 这不是一个真正的选择,因为它是一个众所周知的外部库类。 人们不会让你这样做。
  • 如上所述分叉并修改BeanComparator ,为其提供不同的FQN。
  • 使用实现Comparator的类包装现有的BeanComparator
  • questions类型更改为List
  • 添加抑制警告注释。

由于BeanComparator不是通用的,你只需要压制。

更新:实际上,如果它足够困扰你,你可以分叉代码库使它成为通用的,因为它是开源的。

除非在Apache Commons Beanutils中添加新的generics类,否则我发现最好的是将BeanComparator包装在我的“bean工具箱”中的新方法中:

 /** * Wrapping of Apache communs BeanComparator. Create a comparator which compares two beans by the specified bean * property. Property expression can use Apache's nested, indexed, combinated, mapped syntax. @see Apache's Bean * Comparator for more details. * @param  generic type * @param propertyExpression propertyExpression * @return the comparator */ @SuppressWarnings("unchecked") public static  Comparator createPropertyComparator(final String propertyExpression) { return new BeanComparator(propertyExpression); } 

创建一个通用的包装类:

 public class GenericBeanComparator implements Comparator { private final BeanComparator myBeanComparator; public GenericBeanComparator(String property) { myBeanComparator = new BeanComparator(property); } public int compare(T o1, T o2) { return myBeanComparator.compare(o1, o2); } } 

像这样用它:

 List questions = new ArrayList(); questions.addAll(getAllQuestions()); //returns a set of Questions Collections.sort(questions, new GenericBeanComparator("questionId")); 

是的,您应该使用@SuppressWarnings(“未选中”)。 没有理由认为不使用generics的比较器在这种情况下会导致问题。

您可以随时切换到使用Google Collections。

他们支持generics。

删除警告的唯一方法是更改​​BeanComparator的代码,但即使你可以,除非你使它成为了解你的特定类型的特定包装器,否则这个概念将无法正常工作。 该类通过reflection操作任何对象,该方法可能有也可能没有。 它本质上不是类型安全的。

警告的最简单方法是实现自己的比较器:

  public class QuestionComparator extends Comparator { private BeanComparator peer = new BeanComparator("questionId"); public int compare(Question o1, Question o2) { return peer.compare(o1, o2); } } 

如果重要的话你也可以实现equals,并像这样调用BeanComparator equals方法:

  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); } 

BeanComparator是一个非常小的类。 抓取源代码并像这样修改它:

public class BeanComparator implements Comparator, Serializable {

并修改你的调用,如下所示:

Collections.sort(yourCollection, new BeanComparator(yourProperty));

而且警告消失了。