问题
I am trying to implement a sorted and unsorted array list. Both extend a class called AbstractArrayMyList which contains common operations/implementations - toString, clear, etc....
Here is my code for AbstractArrayMyList(which implements a generic interface I defined)
public abstract class AbstractArrayMyList<E> implements MyList<E> {
protected E[] elementData;
.....
}
I chose to make elementData protected so that sorted and unsorted specialized array lists can access and perform operations on it. Here is my declaration/code for sorted array list
public class ArrayListSorted<E extends Comparable<E>> extends AbstractArrayMyList<E>
This all compiles fine. However when I test my code, with these lines
ArrayListSorted<Integer> toTestInteger = new ArrayListSorted<Integer>()
toTestInteger.insert(0);
assertEquals(toTestInteger.get(0).intValue(), 0);
I get a class cast exception
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at myarraylist.ArrayListSorted.getIndex(ArrayListSorted.java:38)
that occurs here
@Override
public int getIndex(E value) {
int lo = 0;
int hi = size;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (value.compareTo(elementData[mid]) < 0) hi = mid - 1;
The exception occurs on the same line as the compareTo. Does anyone know what the issue is? I defined the bounded wildcard, E extends Comparable, which means that any class that wishes to work with ArrayListSorted must implement the Comparable interface...
I mean i even have the right syntax, from http://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html, type extends class/interface
回答1:
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[]
.
来源:https://stackoverflow.com/questions/28005959/why-am-i-getting-a-class-cast-exceptionwith-generics-comparable