Incompatible types: int[] cannot be converted to Comparable<Object>[]

17,114

Solution 1

You have two issues here:

  1. int is a POD, not an object. Boxing and unboxing from int[] to corresponding Integer[] is not automatically performed. You need to declare intArray as:

    Integer[] intArray = {2,3,5,1};
    
  2. Integer implements Comparable<Integer>, not Comparable<Object>. The two specializations are different and incompatible types. The right way to declare selectionSort 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 objects
  • Comparable<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 allowed
  • Comparable<Integer>[] array = new Integer[] {1,2,3,4}; is valid statement
Share:
17,114
Peterxwl
Author by

Peterxwl

Updated on June 04, 2022

Comments

  • Peterxwl
    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);
      }
    }