Why am i getting a class cast exception(with generics, comparable)?

后端 未结 1 876
灰色年华
灰色年华 2021-01-28 09:09

I am trying to implement a sorted and unsorted array list. Both extend a class called AbstractArrayMyList which contains common operations/implementations - toString, clear, et

相关标签:
1条回答
  • 2021-01-28 09:30

    The problem is that you're using the generic type as the type of the array. Array types are reified (actually present in the JVM) at runtime, but the generic types aren't. This means that your new E[] actually ends up being an Object[] instead of an array of the type you wanted.

    The standard collections deal with this problem by not providing direct access to the array and casting to E on operations like get(). If you really think that using a typed array is the best option, then you'll need to pass Class<E> clazz to the constructor for your abstract base class and use that to construct a correctly-typed array:

    protected AbstractArrayMyList(Class<E> clazz) {
        this.elementClass = clazz;
        this.elementData = Array.newInstance(clazz, INITIAL_SIZE);
    }
    

    The reason you're getting the ClassCastException is that the compiler replaces the method signatures with their erasures, which is basically the greatest common denominator of the acceptable types. Since you're narrowing E from Object to Comparable in your subclass, the signature on that method ends up being Comparable[] instead of Object[].

    0 讨论(0)
提交回复
热议问题