1

This program...

public static void main(String[] args) {

    String[] table = (String[]) new Object[20];

    table[1] = "bla";

}

... generates a cast exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at tests.App.main(App.java:10)

However, the same operation done using generics, do not generate any errors:

public static void main(String[] args) {        

    doIt("bla");

}

public static <V>void doIt(V val) {

    V[] table = (V[]) new Object[20];

    table[1] = val;     
}

Why is it different using generics?

user1883212
  • 7,539
  • 11
  • 46
  • 82

1 Answers1

3

It's because of type erasure. At runtime, V[] is just Object[].

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43