An array of shared objects where the shared object has a different upper bound than Object

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()); // Error
    }
}

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()); // Prints 6
    }
}

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]); // error more ClassCastException

But to do it wrong:

System.out.println(new TestClass<>(2, 6).getItem()); // Prints 6

Does anyone else get the feeling that java type types are a bit inconsistent?

+4
3

generic type , , , , - generic, .

, Comparable T, Comparable[] , T[]. , , Object[], .

, Comparable[] , .

, , , Java?, . Class, .

@SuppressWarnings("unchecked")
public TestClass(int size, Class<T> clazz, T... values) {
    items = (T[]) Array.newInstance(clazz, size);
    // ...
}
+1

,

items = (T[]) new Object[size];

Object [] Comparable ( - ), , Comparable c = (Comparable)(new Object()), Object [] [], .

+2

(T[]) new Object[size] T Object, T extends Comparable<T> :

(T[]) new Comparable[size]

, T . , , T Object, Object[], . , T Comparable<...>, cast Comparable[], , Object[]. Comparable[] .

+1

All Articles