Java Collections.sort - помогает мне удалить предупреждение непроверенное

Ctrl + Сдвиг + 8 - Отслеживание в обратном порядке переходит к предыдущему" F12 / Переходят к определению"

10
задан skaffman 18 May 2012 в 13:27
поделиться

5 ответов

Options are:

  • Change BeanComparator to implement Comparator. 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.
  • Change the type of questions to List.
  • Add a suppress warnings annotation.
10
ответ дан 3 December 2019 в 21:21
поделиться

Поскольку BeanComparator не является универсальным, вам просто нужно подавить.

ОБНОВЛЕНИЕ: На самом деле, если это вас достаточно беспокоит, вы можете разветвить базу кода на сделайте его универсальным, поскольку это открытый исходный код.

5
ответ дан 3 December 2019 в 21:21
поделиться

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.

0
ответ дан 3 December 2019 в 21:21
поделиться

You could always switch to using Google Collections.

They support Generics.

0
ответ дан 3 December 2019 в 21:21
поделиться

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);
   }
0
ответ дан 3 December 2019 в 21:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: