after check for implementation, how to allow method from interface?

Viewed 17

I'm struggling to title this question, but basically this is what is happening. I am implementing a bubblesort algorithm, but obviously, it requires the compareTo method, part of the Comparable interface. So in my method, I added the following:

if(!(array[0] instanceof Comparable)) // dont allow non-comparable objects
     return;

So now on array[j], I'll need to call array[j].compareTo(array[i+j]). But when I do this, there is an error saying that the object does not have compareTo. But I know it does! How can I fix this?

1 Answers

You need to cast it

((Comparable)array[j]).compareTo(array[i+j])

Anyway it's not proper approach to fix this issue. Instead, your array should be Comparable[] or the type of array should either inherit from this interface or require compareTo method

Related