1
\$\begingroup\$

My code works, but my IDE is giving me warnings for unchecked method invocation. I have found useful information about Comparable arrays here. I have found useful information about unchecked method invocation here. Despite this, I just can't figure out how to please my IDE. My intention is to have the method selectionSort sort an array of either Integers or Doubles using compareTo.

import java.util.Arrays;

class Main{
    public static void main(String[] args){

        Comparable[] data0 = {2, 8, -39, 904, 8, 0};
        Comparable[] data1 = {1.1, -5.68, 4.39, -0.01, 5.59};

        System.out.printf("Unsorted array: %s%n%n", Arrays.toString(data0));
        selectionSort(data0);
        System.out.printf("%nSorted array: %s%n", Arrays.toString(data0));

        System.out.printf("Unsorted array: %s%n%n", Arrays.toString(data1));
        selectionSort(data1);
        System.out.printf("%nSorted array: %s%n", Arrays.toString(data1));
    }

    private static <T extends Comparable<T>> void selectionSort(T[] data){
        for(int i = 0; i < data.length - 1; ++i){
            int smallest = i;

            for(int index = i + 1; index < data.length; ++index){
                if (data[smallest].compareTo(data[index]) > 0){
                    smallest = index;
                }
            }

            swap(data, i, smallest);
            printPass(data, i + 1, smallest);
        }
    }

    private static <T> void swap(T[] data, int first, int second){
        T temporary = data[first];
        data[first] = data[second];
        data[second] = temporary;
    }

    private static <T> void printPass(T[] data, int pass, int index){
        System.out.printf("after pass %2d: ", pass);

        for(int i = 0; i < index; ++i){
            System.out.printf("%s ", data[i]);
        }

        System.out.printf("%s* ", data[index]);

        for(int i = index + 1; i < data.length; ++i){
            System.out.printf("%s ", data[i]);
        }

        System.out.printf("%n               ");

        for (int j = 0; j < pass; j++){
            System.out.printf("-- ");
        }
        System.out.println();
    }
}
\$\endgroup\$
1
\$\begingroup\$

When I put this into IntelliJ with my default settings I already get a warning on the Comparable[] data0 declaration.

Raw use of parameterized class

Changing the array declarations to these:

Integer[] data0 = {2, 8, -39, 904, 8, 0};
Double[] data1 = {1.1, -5.68, 4.39, -0.01, 5.59};

solved both warnings.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.