Tuesday, September 18, 2012

A good question for quiz about generics In Java

Suppose you have two classes:
public class Foo {
 private String[] array = (String[]) new Object[];

 public static void main() {
  Foo f = new Foo();
 }
}

public class Bar<T> {
 private T[] array = (T[]) new T[];

 public static void main() {
  Bar b = new Bar<String>();
 }
}
Will they compile? Will they run? At a first glance it may seem that both make inappropriate casting from superclass Object[] to subclass String[]. But if you look more carefully you may see that compiler replaces T[] with Object[], so class Bar compiles and runs without errors while Foo can't compile due to improper cast.