英文:
Unchecked or unsafe operations without using annotation
问题
我从一本我正在阅读的书中复制了这些代码...
import java.util.Comparator;
public class DefaultComparator<E> implements Comparator<E> {
public int compare(E a, E b) throws ClassCastException {
return ((Comparable<E>) a).compareTo(b);
}
}
但它会产生一个编译器警告,指出它使用了未经检查或不安全的操作。那么,在不使用注解@SuppressWarnings("unchecked")
的情况下,我该如何消除这个警告呢?
英文:
I copied this piece of codes from a book I am currently reading...
import java.util.Comparator;
public class DefaultComparator<E> implements Comparator<E> {
public int compare(E a, E b) throws ClassCastException {
return ((Comparable<E>) a).compareTo(b);
}
}
but it throws a compiler warning that it uses unchecked or unsafe operations. So how can I remove the warning without using the annotation @SuppressWarnings("unchecked")
?
答案1
得分: 3
你需要确保 E 扩展了 Comparable 类:
public class DefaultComparator<E extends Comparable<E>> implements Comparator<E> {
public int compare(E a, E b) {
return a.compareTo(b);
}
}
英文:
You need to make sure that E is extending the Comparable class:
public class DefaultComparator<E extends Comparable<E>> implements Comparator<E> {
public int compare(E a, E b) {
return a.compareTo(b);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论