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

百般思念 提交于 2019-12-02 12:30:13

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[].

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!