【问题标题】:"instanceof" check throws CompileTimeError "cannot safely cast"“instanceof”检查抛出 CompileTimeError “无法安全转换”
【发布时间】:2021-10-18 19:48:03
【问题描述】:

我有这个内部类节点,我在实例检查中得到这个奇怪的错误。我试图谷歌,这是为什么,但它只显示“不可转换类型”错误,事实并非如此。我也尝试让 Node 成为一个静态类,但这也无济于事。我对此有点困惑,因此将不胜感激您的帮助。提前致谢。

import java.util.Objects;

public abstract class Graph<E> {
    protected class Node {
        E item;

        protected Node(final E item) {
            this.item = item;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o)
                return true;
            else if(item == null)
                return false;
            else if(o instanceof final Node node) //error: "java: java.lang.Object cannot be safely cast to Graph<E>.Node"
                return item.equals(node.item);

            return item.equals(o);
        }

        @Override
        public int hashCode() {
            return Objects.hash(item);
        }
    }
}

在阅读了一些答案后,我意识到我只犯了一个愚蠢的错误,在这段代码中得到了纠正:

import java.util.Objects;

public abstract class Graph<E> {
    protected class Node {
        E item;

        protected Node(final E item) {
            this.item = item;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o)
                return true;
            else if(item == null)
                return false;
            else if(o instanceof final /* Error was not using a wildcard*/ Graph<?>.Node node) //also after some confusion this (final Node node) is a java 16 feature
                return item.equals(node.item);

            return item.equals(o);
        }

        @Override
        public int hashCode() {
            return Objects.hash(item);
        }
    }
}

【问题讨论】:

  • 对。通配符。忘了那个。我尝试使用 E 显然没有用。

标签: java pattern-matching instanceof


【解决方案1】:

我认为问题在于,您在参数化类中使用了内部类。并且 instanceof 检查不知道应该对哪个参数进行强制转换。

【讨论】:

  • 是的,解决方法是使用通配符,正如@user16320675 提到的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多