3

I have the following simple code:

class GenClass<T> {
    T method1(T in) {
        T[] arr = (T[])new Object[10];
        arr[1] = in;
        return arr[1];
    }
}

public class TestClass {
    public static void main(String[] args) {     
        GenClass<Integer> cl = new GenClass<>();
        System.out.println(cl.method1(1000));

        Integer[] arr = (Integer[])new Object[10];   
        arr[1] = 1000;
        System.out.println(arr[1]);
    } 
} 

The result is the following:

1000
Exception in thread "main" java.lang.ClassCastException: 
[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at javaapplication8.TestClass.main(TestClass.java:17)
Java Result: 1

So why this code work well:

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

and this code throw run-time error:

Integer[] arr = (Integer[])new Object[10]; 

?

Is it because of type erasure?

If so - is "T" at run-time just being exchanged with "Object" in method1 so the source code:

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

became the following at run-time:

Object[] arr = (Object[])new Object[10];

?

Or something different is heppened?

nik
  • 365
  • 1
  • 4
  • 15
  • The keyword is [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html), i.e. at runtime `T[] arr = (T[])new Object[10];` becomes `Object[] arr = (Object[])new Object[10];`. – Thomas Aug 03 '16 at 09:53
  • 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 Aug 03 '16 at 09:56

1 Answers1

3

You are correct, generic cast works because of type erasure: Java compiler turns this

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

into

Object[] arr = (Object[])new Object[10];

so the cast succeeds.

Non-generic cast, on the other hand, tries to cast an array of Objects to an incompatible type

Integer[] arr = (Integer[])new Object[10]; 

thus causing an error.

The rest of generic code works fine, because the assignment of an Integer into Object[] array is allowed. In fact, you can do it without a cast:

Object[] arr = new Object[10];   
arr[1] = 1000;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523