Who can explain what is happening in the following scenarios? Why does one give an error, and the other doesn't?
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()); // Error
}
}
Executing the above 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()); // Prints 6
}
}
I should also mention that the creation of the array is done in a super class, so I cannot change the way the array initialization is done. Also this is compiled under Java 8
The solution I went with was to do this:
this.items = (T[])new Comparable[size];
The above only works so long as you are not trying to use the array outside your class. So doing this for example is an error:
TestClass<Integer> t = new TestClass<>(2, 6);
System.out.println(t.items[0]); // error more ClassCastException
But doing this isn't:
System.out.println(new TestClass<>(2, 6).getItem()); // Prints 6
Anyone else get the feeling that java generic types are a tad bit inconsistent?