corresponding to the title, my problem is to get the array-length of an generic array, which is inside an instance of an class, which has been initialized with this generic type. When i want to get the length of my array (ak.array.length), java throws this error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; at Testclass.main(Testclass.java:15)
So where is my fault in this code? Thanks in advance
public class Testclass {
static class ArrayKeeper<T> {
protected T[] array;
public ArrayKeeper() {
array = (T[])new Object[5];
}
}
public static void main(String[] args) {
//create a new instance of inner class ArrayKepper (type String)
Testclass.ArrayKeeper<String> ak = new Testclass.ArrayKeeper<String>();
System.out.println(ak.array.length); //cast error here.
}
}