2013-06-01 49 views
2

我在使用msort方法時遇到問題。我沒有任何錯誤,但是當我編譯, 我在下面一行得到一個錯誤:Msort錯誤,通用

if (((Comparable)arr[midpt-1]).compareTo(arr[midpt]) <= 0) 

錯誤說:

方法的CompareTo(對象)屬於原類型爲Comparable。可比較的泛型類型的引用應該被參數化。

有幫助嗎?

private static void msort(Object[] arr, Object[] tempArr, int first, int last) 
{ 
    // if the sublist has more than 1 element continue 
    if (first + 1 < last) 
    { 
     // for sublists of size 2 or more, call msort() 
     // for the left and right sublists and then 
     // merge the sorted sublists using merge() 
     int midpt = (last + first)/2; 

     msort(arr, tempArr,first, midpt); 
     msort(arr, tempArr, midpt, last); 

     // if list is already sorted, just copy from src to 
     // dest. this is an optimization that results in faster 
     // sorts for nearly ordered lists. 
     if (((Comparable)arr[midpt-1]).compareTo(arr[midpt]) <= 0) 
      return; 

     // the elements in the ranges [first,mid) and [mid,last) are 
     // ordered. merge the ordered sublists into 
     // an ordered sequence in the range [first,last) using 
     // the temporary array 
     int indexA, indexB, indexC; 

     // set indexA to scan sublist A (index range [first,mid) 
     // and indexB to scan sublist B (index range [mid, last) 
     indexA = first; 
     indexB = midpt; 
     indexC = first; 

     // while both sublists are not exhausted, compare arr[indexA] and 
     // arr[indexB]; copy the smaller to tempArr 
     while (indexA < midpt && indexB < last) 
     { 
      if (((Comparable)arr[indexA]).compareTo(arr[indexB]) < 0) 
      { 
       tempArr[indexC] = arr[indexA]; // copy element to tempArr 
       indexA++;      // increment indexA 
      } 
      else 
      { 
       tempArr[indexC] = arr[indexB]; // copy element to tempArr 
       indexB++;      // increment indexB 
      } 
      // increment indexC 
      indexC++; 
     } 

     // copy the tail of the sublist that is not exhausted 
     while (indexA < midpt) 
     { 
      tempArr[indexC] = arr[indexA]; // copy element to tempArr 
      indexA++; 
      indexC++; 
     } 

     while (indexB < last) 
     { 
      tempArr[indexC] = arr[indexB]; // copy element to tempArr 
      indexB++; 
      indexC++; 
     } 

     // copy elements from temporary array to original array 
     for (int i = first; i < last; i++) 
     arr[i] = tempArr[i]; 
    } 
} 

回答

3

你不能擺脫所有的警告,而無需使用@Suppresswarnings因爲你執行的是未經檢查的強制轉換爲Comparable

既然你在內部要求將你Object s爲強制轉換爲Comparable,它會更有意義,宣佈在你的方法聲明:

private static <T extends Comparable<T>> void msort(T[] arr, T[] tempArr, int first, int last) { 

那麼你比較列簡直變成:

if (arr[midpt - 1].compareTo(arr[midpt]) <= 0) {