Domanda

Okay, so I am trying to write a generic sorting package in Java (I'm taking an algorithms course and I see it as good practice, both in the algorithmic sense and in Java as I'm very new to the language). Anyway, I figure the best way to do this is to create a Sort class with multiple sorting methods within, such as insertionSort, mergeSort etc. If you feel there's a better way of doing this, please let me know as a comment as I am always open to suggestions for writing cleaner and more efficient code.

As for the question:

I have the backbone structure down and want to try coding the insertionSort method first. However, I have tried to pass it an integer array but am getting some problems. Firstly, with generics I understand that you have to use <Integer> as opposed to <int>, but for some reason if I create an array such as int[] arr = new int[]{..} and pass this in to the generic it does not work. How do I fix this without using Integer[] arr = new Integer[]{..}? I was under the impression that the compiler would box my int to Integer automatically?

My code:

public class Sort<T> {
    public T[] insertionSort(T[] array) {
        // do some stuff
        return array;
    }

    public static void main(String[] args) {
        int[] orig = new int[]{1,35,3,2,4634,2,46,7,33,56};
        Sort<Integer> sorter = new Sort<Integer>();
        sorter.insertionSort(orig);
    }
}
È stato utile?

Soluzione

How do I fix this without using Integer[] arr = new Integer[]{..}?

You don't. This simply won't work.

I was under the impression that the compiler would box my int to Integer automatically?

It will, for individual int to Integer values. But there's no conversion from int[] to Integer[]... so combined with the lack of primitive support in Java generics, a method taking a T[] simply cannot take an int[].

There are third-party libraries which have conversion methods, but they will always create a new array, rather than creating a view onto the existing array. (It would be possible to create a List<Integer> which was a view onto the existing array, although obviously add operations would have to fail, as would set operations with a null value.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top