Why do I get "Illegal generic type for instanceof"?

Viewed 26930

Given:

public class C<T> {
    private class D {
        public boolean equals( Object o ) {
            if ( !(o instanceof D) )    // line 4
                return false;
            D other = (D)o;             // line 6
            return i == other.i;
        }
        int i;
    }
}

I get:

C.java:4: illegal generic type for instanceof
          if ( !(o instanceof D) )
                              ^

I also get an "unchecked cast" warning about line 6. Why? The o is not a generic type -- it's just a plain Object. How can I correctly implement equals() by both checking for and casting to an instance of D?

Note: Obviously, this code example is a whittled-down version of my actual code. The real classes for C and D are much larger and D is a private inner class of C used by its implementation.

FYI: The real D does make use of the generic parameter T.

4 Answers
Related