Tony
Tony

Reputation: 479

Generics array cast

I've got the following code:

public class GenericsTest<T> {

        private T[] array1;
        private String[] array2;

        public GenericsTest() {
            array1 = (T[]) new Object[10];
            array2 = (String[]) new Object[10];
        }

        public T[] getArray1() {
            return array1;
        }

        public void setArray1(T[] array1) {
            this.array1 = array1;
        }

        public String[] getArray2() {
            return array2;
        }

        public void setArray2(String[] array2) {
            this.array2 = array2;
        }

        public static void main(String[] args) {
            new GenericsTest<String>();
        }

    }

Code crushes at line:

array2 = (String[]) new Object[10];

But it works fine with:

array1 = (T[]) new Object[10];

As you can see in main() method, T is a String. So I guess compiler will change T to String in

private T[] array1;

and array1 = (T[]) new Object[10] will be translated to array1 = (String[]) new Object[10]

So why array2 = (String[]) new Object[10] fails and (T[]) new Object[10] doesn't?

Upvotes: 0

Views: 73

Answers (2)

sham
sham

Reputation: 3801

A generic type T is a generic Object type, and can be cast to an Object so like: (Object[]) new Object[10])

Meanwhile String extends Object and so you cannot cast upwards.

Upvotes: 0

degr
degr

Reputation: 1565

because generic types will be lost after compilation, and all your generic <T> will be transformed into Object, so, when you do

(T[]) new Object[10];

it is equal to

(Object[]) new Object[10];

And of course it is not equal to

(String[]) new Object[10];

Upvotes: 3

Related Questions