我在NetBeans中编写了类似这样的代码:
public class Grafo<V, E>
{
class Par
{
int a, b;
Par(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object ob)
{
if(ob instanceof Par) {
Par p = (Par)ob;
return this.a==p.a && this.b==p.b;
}
return false;
}
}
//stuff...
} //end of class Grafo
错误来自内部类“Par”的方法equals()。
NetBeans说错误是“非法泛型类型的instanceof”。错误在下面的行中。
if(ob instanceof Par) {
错误的原因是什么?
答案 0 :(得分:7)
尝试ob instanceof Grafo<?,?>.Par
我认为编译器认为ob instanceof Par
涉及对泛型类型参数的运行时检查;即它相当于ob instanceof Grafo<V,E>.Par
。但instanceof
测试无法检查泛型类型参数。
答案 1 :(得分:4)
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object ob)
{
if(ob instanceof Grafo.Par) {
Par p = (Par)ob;
return this.a==p.a && this.b==p.b;
}
return false;
}
或定义您的内部班级static