0

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?

Tony
  • 387
  • 1
  • 4
  • 16
  • I do not see the point of using parameterized type T if you know it is always String – HRgiger Sep 20 '16 at 13:53
  • I don't think you can cast a Object[] into a String[], why not just make array2 to new String[] instead of an Object[] – Jason White Sep 20 '16 at 13:56
  • Possible duplicate of [Java generics - type erasure - when and what happens](http://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens) – Tom Sep 20 '16 at 14:01
  • So since you are testing, String is immutable but you have also options like GenericsTest or GenericsTest – HRgiger Sep 20 '16 at 14:05
  • This code emits compiler warnings for a reason. Generics are not compatible with arrays; always use Lists (or at least Collections) instead. – VGR Sep 20 '16 at 16:21

2 Answers2

3

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];
degr
  • 1,301
  • 1
  • 13
  • 33
0

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.

sham
  • 3,269
  • 3
  • 12
  • 21