我目前正在 Java 中實現最長遞增子序列問題的通用版本。該方法按預期工作,但當我嘗試使用 Comparable[] 而不是 Integer[](或 int[])時,程序無法編譯。給出的錯誤是“Comparable cannot be cast to Integer”。我了解錯誤及其含義,但不知道如何解決。任何幫助將不勝感激 :)我已經嘗試將方法的返回類型設為泛型 (>),但問題是 Java 不允許創建泛型數組。我試過只使用 Integer[] 作為我的返回類型,雖然編譯和工作正常,但這不是我想要的。public class LIS { public static void main(String[] args) { final Integer[] arr = {-1, 2, 4, 2, 33, 4, 7, 8, 10, 7, 5, 4, 5, 5, 1}; final Integer[] LIS = (Integer[]) lis(arr); for (int i : LIS) { System.out.print(i + " "); } } public static Comparable[] lis(Comparable[] arr) { // We use Comparable[] so we can use interchangably with any Comparable type final int N = arr.length; // Java conveniently initializes array values to 0: int[] lisEndingHere = new int[N]; for (int i = 0; i < N; i++) { lisEndingHere[i] = 1; int curMax = 0; for (int j = 0; j <= i; j++) { if (arr[i].compareTo(arr[j]) <= 0) continue; if (lisEndingHere[j] > curMax) { curMax = lisEndingHere[j]; } } lisEndingHere[i] += curMax; } // Find and return the longest increasing subsequence: int max = 0; for (int i = 0; i < N; i++) { if (lisEndingHere[i] > max) max = lisEndingHere[i]; } Comparable[] LIS = new Comparable[max]; for (int i = N-1; i >= 0 && max != 0; i--) { if (lisEndingHere[i] == max) { LIS[--max] = arr[i]; } } return LIS; }}
2 回答

翻閱古今
TA貢獻1780條經驗 獲得超5個贊
換行就行
final Integer[] LIS = (Integer[]) lis(arr);
到
final Comparable[] LIS = lis(arr);
并更新 for 循環。
您的方法返回一個 Comparable 數組,因此您不能向下轉換為 Integer 數組,但由于您的數字的實現是 Integers,因此在運行時它們仍然被視為整數。
無論如何,將結果設置為 Integer 數組與創建泛型方法的目的背道而馳。對于要傳遞給你的方法的東西,它必須有一個 compareTo 方法,并且固有地有一個 toString 方法,并且它滿足你需要程序做的一切。

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
這里沒有什么可以解決的。這里:
Integer[] LIS = (Integer[]) lis(...)
您的方法 lis() 返回一個 Comparable 對象數組。Comparable 數組不是 Integer 數組!因此,該轉換在概念上不起作用。
是的,該數組包含 Integer 對象,但數組類型不是“整數數組”。
您必須迭代結果數組,然后才能投射各個條目。但是你不能將數組類型本身轉換成它不是的東西!
除此之外,您可以將泛型與列表一起使用。
添加回答
舉報
0/150
提交
取消