For class we have to implement data structures in java without using those already implemented by default, so no I cannot use Lists
. Previously there were situations where it was necessary to create an array of a generic type T
and the following works without problem:
class Test<T> {
private T[] array;
@SuppressWarnings("unchecked")
public Test(int sz) {
array = (T[]) new Object[sz];
}
public static void main(String[] args) {
Test test = new Test(1);
}
}
Now instead of an array of type T
, it was necessary to create an array of type Thing<T>
where Thing is a class... The same approach gives runtime error (java.lang.ClassCastException):
class Thing<T> { }
class Test<T> {
private Thing<T>[] array;
@SuppressWarnings("unchecked")
public Test(int sz) {
array = (Thing<T>[]) new Object[sz];
}
public static void main(String[] args) {
Test<Object> test = new Test<>(1);
}
}
What can be done about the second case?