albatrus
albatrus

Reputation: 11

Why should we cast to the same type?

can anyone explain why am i getting incompatible type error and should cast to Object[] if ref[0] is already object array(class [Ljava.lang.Object;)

public class Test {
    public static void main(String args[]) {
        Object[] ref = new Object[1];
        Object[] x = new Object[]{1};
        while (true) {
            ref[0] = new Object[]{ref};
            System.out.println(ref[0].getClass()); //class [Ljava.lang.Object;
            ref = ref[0]; // incompatible type error
        }

    }
}

Upvotes: 1

Views: 46

Answers (1)

xingbin
xingbin

Reputation: 28289

At compile stage, ref[0]'s data type is Object, ref's data type is Object[].

Object and Object[] are not the same type.

Upvotes: 3

Related Questions