I've tried to understand how generics works. I created several implementations sorting algorithms and before sorting i shuffling input array by shuffleArray method in AbstractSorter.java:
public class AbstractSorter<T extends Comparable> {
public void swap(final T[] input, int srcPos, int dstPos) {
if (dstPos != srcPos) {
T accum = input[dstPos];
input[dstPos] = input[srcPos];
input[srcPos] = accum;
}
}
public T[] shuffleArray(final T[] inputArray) {
// E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];
T[] result = (T[]) new Comparable[inputArray.length];
System.arraycopy(inputArray, 0, result, 0, inputArray.length);
int index;
Random random = new Random();
for (int i = result.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
if (index != i) {
swap(result, i, index);
}
}
return result;
}
public boolean more(final T x, final T y) {
return (x.compareTo(y) > 0);
}
but when i try to use like this:
AbstractSorter<Integer> sortHelper = new AbstractSorter();
Integer[] expResult = new Integer[]{-30, -29, -28, -27 };
Integer[] shuffleArray = sortHelper.shuffleArray(expResult);
System.out.println("Array ="+Arrays.toString(shuffleArray));
it i got exception:
java.lang.ClassCastException:
[Ljava.lang.Comparable; cannot be cast to [Ljava.lang.Integer;
I don't understand how can i fix shuffle method. Is it possible implement this functionality on arrays or should i migrate to collections?
Thanks in advance!