“instanceof 的非法泛型类型”在内部类类型上使用instanceof时?

发布于 2024-08-14 07:02:08 字数 674 浏览 2 评论 0原文

我在 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) {

错误的原因是什么?

I coded in NetBeans something like this:

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

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在风中等你 2024-08-21 07:02:08

尝试 ob instanceof Grafo.Par

我认为编译器认为 ob instanceof Par 涉及对泛型类型参数的运行时检查;即它相当于 ob instanceof Grafo.Par。但是 instanceof 测试无法检查泛型类型参数。

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.

心奴独伤 2024-08-21 07:02:08
@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

@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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文