开发者

"illegal generic type of instanceof" when using instanceof on an inner class type?

I coded in NetBeans something like this:

public class Grafo<V, E&开发者_运维百科gt;
{
    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

The error is in the method equals() from inner class "Par".

NetBeans says that the error is "illegal generic type of instanceof". The error is in the line below.

            if(ob instanceof Par) {

What is the cause of the error ?


Try ob instanceof Grafo<?,?>.Par

I think that the compiler thinks that ob instanceof Par involves a runtime check on generic type parameters; i.e. that it is equivalent to ob instanceof Grafo<V,E>.Par. But instanceof tests cannot check generic type parameters.


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

Or define your inner class static

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜