Search code examples
javapattern-matchinginstanceof

"instanceof" check throws CompileTimeError "cannot safely cast"


I have this inner class Node, where I get this weird error on an instanceof check. I tried to google, why this was, but it only showed "inconvertible types" errors, which this is not. I also tried to make Node a static class, but that didn't help either. I'm a little confused with this so your help would be greatly appreciated. Thanks in advance.

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

After reading some answer I realized I made just one silly mistake which is corrected in this piece of code:

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

Solution

  • I think the problem is, that you use a inner class in a parameterized class. And the instanceof check does not know, for which parameter the cast should be done.