我試着瞭解泛型如何工作。我創建了幾個實現排序算法和排序之前,我洗牌輸入數組由shuffleArray方法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);
}
但是當我嘗試使用這樣的:
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));
它我得到例外:
java.lang.ClassCastException:
[Ljava.lang.Comparable; cannot be cast to [Ljava.lang.Integer;
我不明白我該如何修復洗牌方法。是否有可能在陣列上實現此功能或者我應該遷移到集合?
在此先感謝!
什麼是錯的內置的Shuffle方法爲什麼不使用它? https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util。列表) – StackFlowed
不應該是'T延伸可比較的'? –
maraca
@StackFlowed我使用數組並且不想遷移到列表。但是,如果沒有其他方式,我會。 –