I have two classes, AbstractArrayMyList class and a ArrayListSorted class, which extends AbstractArrayMyList.
Here is my declaration for AbstractArrayMyList and pertinent constructors
public abstract class AbstractArrayMyList<E extends Comparable<E>> implements MyList<E> {
private static final int DEFAULT_CAPACITY = 100;
protected E[] elementData;
public AbstractArrayMyList() {
this( DEFAULT_CAPACITY);
}
public AbstractArrayMyList( int capacity) {
elementData = (E[]) new Object[capacity];
}
with MyList being the adt interface
And my ArrayListSorted class(with pertinent constructor),
public class ArrayListSorted<E extends Comparable<E>> extends
AbstractArrayMyList<E> {
public ArrayListSorted() {
super();
}
}
Here is the line of code that is causing the class cast exception. (just creating an array list sorted class with bounded type Integer. Im really confused about why this exception is occurring.
ArrayListSorted<Integer> toTestInteger = new ArrayListSorted<Integer>();
chrylis explained from here, Why am i getting a class cast exception(with generics, comparable)? that the issue was that the jvm sees my new Object[capacity] as an object array. I agree with that point but that was when the definition for my AbstractArrayMyList was still
public abstract class AbstractArrayMyList<E> implements MyList<E>
, meaning that the jvm has to treat E as on object because it knows nothing else about it. But since i added E extends Comparable shouldn't this cast be allowed? JVM will recognize this as an array of comparable objects?