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