Who can explain what happens in the following scenarios? Why does an error occur and the other does not?
public class TestClass<T extends Comparable<T>> {
protected T []items;
public TestClass(int size, T... values) {
items = (T[]) new Object[size];
for (int v = 0; v < Math.min(size, values.length); v++) {
items[v] = values[v];
}
}
public T getItem() {
return items[0];
}
public static void main(String []args) {
System.out.println(new TestClass<>(2, 6).getItem());
}
}
Executing the specified class gives the following error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at TestClass.<init>(TestClass.java:5)
at TestClass.main(TestClass.java:16)
Java Result: 1
And there is this:
public class TestClass<T> {
protected T []items;
public TestClass(int size, T... values) {
items = (T[]) new Object[size];
for (int v = 0; v < Math.min(size, values.length); v++) {
items[v] = values[v];
}
}
public T getItem() {
return items[0];
}
public static void main(String []args) {
System.out.println(new TestClass<>(2, 6).getItem());
}
}
I should also note that creating the array is done in the superclass, so I cannot change the way the array is initialized. Also compiled for Java 8
The solution I went with was to do this:
this.items = (T[])new Comparable[size];
The above only works if you are not trying to use an array outside of your class. So, for example, this is an error:
TestClass<Integer> t = new TestClass<>(2, 6);
System.out.println(t.items[0]);
But to do it wrong:
System.out.println(new TestClass<>(2, 6).getItem());
Does anyone else get the feeling that java type types are a bit inconsistent?