Incompatible types: int[] cannot be converted to Comparable<Object>[]
Solution 1
You have two issues here:
int
is a POD, not an object. Boxing and unboxing fromint[]
to correspondingInteger[]
is not automatically performed. You need to declareintArray
as:Integer[] intArray = {2,3,5,1};
Integer
implementsComparable<Integer>
, notComparable<Object>
. The two specializations are different and incompatible types. The right way to declareselectionSort
is by using generics, as you suggest in the title:public static <T extends Comparable<T>> void selectionSort(T[] input)
Solution 2
You have two issues in your code snippet
The fist one is with the argument of your method, lets look on this example
void simple(Comparable<Object> input) {}
This simple method expect a instance of Comparable<Object>
.
To create a instance for that you could implement class like:
class MyComparable implements Comparable<Object> {}
What you must by aware is that genericType ( className ), assure your type safety. This mean that:
Comparable<String>
can compare only String objectsComparable<Object>
can compare only Object objects
You can not really on class hierarchy in term of generic parameters.
The class Integer
implements Comparable<Integer>
so to be able to use that you can do this:
void simple(Comparable<Integer> input) {}
The you will be able pass everything that implements Comparable<Integer>
.
With arrays is the same rule,
void array(Comparable<Integer>[] input) {}
but what you should keep in mind is that int[]
is not the same as Integer[]
JVM use different operations for those types.
An int[]
stores primitive integer values.
And Integer[]
stores references to Integer
class.
Comparable<Integer>[] array = {1,2,3,4};
is not allowedComparable<Integer>[] array = new Integer[] {1,2,3,4};
is valid statement
Peterxwl
Updated on June 04, 2022Comments
-
Peterxwl almost 2 years
I am new to generics and casting issues. I try to sort any type array that is comparable. The error is as the title; and the code is as below: and error is same for integer. What is the problem and why?
class Sort{ public static void selectionSort(Comparable<Object>[] input) {/* selection Sort Alg*/} public static void main((String[] args){ int[] intArray = {2,3,5,1}; Sort.selectionSort(intArray); } }