Getting compile-time error when sorting arrays using generics in java

Here is my code:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class SortingUsingGenerics {

    public static void main(String[] args) {
        Integer[] intArray = {1,5,4,2,10};
        String[] stringArray = {"ร„","X","C","B","M"};
        Float[] floatArray = {1.5f,2.8f,0.5f,10.3f,9.5f};

        // Sort and Print
        printArray(sortArray(intArray));
        printArray(sortArray(stringArray));
        printArray(sortArray(floatArray));

    }

    private static <MyArray> void printArray(MyArray[] inputArray) {
        for (MyArray element : inputArray) {
            System.out.print(element);
        }
        System.out.println();
    }

    public static <E> E[] sortArray(E[] inputArray){

        if (inputArray instanceof Integer[]){
            Collections.sort(Arrays.asList(inputArray),new Comparator<Integer>() {
                        public int compare(Integer o1, Integer o2) {
                            if (o1 == o2) {
                                return 0;
                            } else if (o1 > 02) {
                                return 1;
                            } else {
                                return -1;
                            }
                        }

                    });
        }
        return inputArray;
    }
}

The error I get is:

Method sort(List<T>, Comparator<? super T>)in type Collections is not applicable for arguments(List<E>, new Comparator<Integer>(){})

Could you explain what I'm doing wrong here?

+4
source share
2 answers

Your check instanceofdoes not really tell the compiler what it inputArrayis Integer[]- the compile time type is still simple E[].

However, you can easily distinguish, and at this point it will work:

if (inputArray instanceof Integer[]) {
    Integer[] integers = (Integer[]) inputArray;
    Collections.sort(Arrays.asList(integers), ...);
}

Or even just:

if (inputArray instanceof Integer[]) {
    Collections.sort(Arrays.asList((Integer[]) inputArray), ...);
}

However, when you have a general method, and then take specific actions for certain types, you should at least consider whether you really need a general method.

+7

, , Integer[], a Float[] String[] - Comparable. , -, Comparable, Comparator, .

, Comparable .

public static <E extends Comparable<E>> E[] sortArray(E[] inputArray){
    Collections.sort(Arrays.asList(inputArray), new Comparator<E>() {
        @Override
        public int compare(E o1, E o2) {
            return o1.compareTo(o2);
        }

    });
    return inputArray;
}

, E , Comparable, compareTo, Comparator.

+3

All Articles