未经批准或不安全的操作,未使用注释。

huangapple go评论68阅读模式
英文:

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&lt;E&gt; implements Comparator&lt;E&gt; {
    public int compare(E a, E b) throws ClassCastException {
        return ((Comparable&lt;E&gt;) 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(&quot;unchecked&quot;)?

答案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&lt;E extends Comparable&lt;E&gt;&gt; implements Comparator&lt;E&gt; {
    public int compare(E a, E b) {
        return a.compareTo(b);
    }
}

huangapple
  • 本文由 发表于 2020年7月25日 20:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63088524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定