This is magic! Look at this simple code:
public class ArrayOFMagic<T> {
protected T[] array;
protected int showMeYouRLength() {
return array.length;
}
ArrayOFMagic() {
array = (T[]) new Object[10];
}
protected void set(T value, int index) {
array[index] = value;
}
public static void main(String[] args) {
ArrayOFMagic<Integer> arrayOFMagic = new ArrayOFMagic<Integer>();
System.out.println(arrayOFMagic.showMeYouRLength());
System.out.println("MAGIC INCOMING");
System.out.println(arrayOFMagic.array.length);
}
}
Output:
10
MAGIC INCOMING
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at ArrayOFMagic.main(ArrayOFMagic.java:25)
I call array.length two times. Once through method and once directly. It proceeds when using method and throws exception when called directly. O.o Someone explain?
edit: Just to clarify: Class works good when not called directly. You can have setters/getters on array elements and all..!