0

I'm trying to write a generic container and I have to use an array. I get the following error :

Exception in thread "main" java.lang.ClassCastException: 
[Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

Here is a portion of my code :

class MinFo<T extends Comparable> {

private final T[] array;

MinFo(int size){
array = (T[]) new Object[size];

}

T get(){

if(this instanceof Comparable){

int tmpPos = getNotNull();
T tmp = array[tmpPos];
int pos;    
for(pos = tmpPos ; pos < array.length; getNotNull()){

    if(tmp.compareTo(array[pos]) > 0)
    tmp = array[pos];
}

which led me to remove the "extends Comparable" from the class declaration. Now I have a different error :

error: cannot find symbol
    if(tmp.compareTo(array[pos]) > 0)
          ^
symbol:   method compareTo(T)
location: variable tmp of type T
where T is a type-variable:
 T extends Object declared in class MinFo

It seems to me that I can't win. Thanks in advance for your help.

cete3
  • 617
  • 5
  • 19

2 Answers2

5

Well yes, this is the problem:

array = (T[]) new Object[size];

If you change that to:

array = (T[]) new Comparable[size];

then it should be okay. The thing is, the cast to T[] is only (at execution time) a cast to Comparable[] as the upper bound of T is Comparable.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
0

Object doesn't actually implement Comparable, so that declaration won't work.

One answer that may be relevant. And another; I think they explain it better than I could.

Community
  • 1
  • 1
Marconius
  • 673
  • 1
  • 5
  • 13