[英]Sorting an array of Integers with generics (Java)
我是目前從事Java工作的二年級計算機科學專業的學生,我們最近開始使用仿制葯。 我有一個任務,我已經獲得了一個使用泛型的排序算法列表,我的任務是使用它們來排序整數列表(不是原始的int)。 由於排序類使用擴展Comparable的泛型,我認為簡單地將它們交給Integer數組沒有問題,但是構建輸出不斷出現不兼容的類型。
相關代碼如下;
主程序的一部分
final int NUMITEMS = 100000;
Integer[] list = new Integer[NUMITEMS];
int dataSize = 0;
//method reads contents of a file into array and returns number of objects
System.out.println((dataSize = readDataFile(list)));
SelectionSort SS = new SelectionSort(list, dataSize);//problem is here
並且提供並期望按原樣使用的SelectionSort算法
class SelectionSort<T extends Comparable<? super T>> implements SortAlgorithm<T> {
public void sort ( T [ ] theArray, int size ) {
for (int last = size-1; last > 0 ; last--)
{
int largest = 0;
for (int scan = 1; scan <= last; scan++)
if (theArray[scan].compareTo(theArray[largest])>0)
largest = scan;
/** Swap the values */
T temp = theArray[largest];
theArray[largest] = theArray[last];
theArray[last] = temp;
}
} // method selectionSort
我遇到的問題是聲明SelectionSort,它返回一個錯誤,表明構造函數不能應用於給定的類型。 從我在這里和其他地方的搜索中看到的這種問題通常在使用整數時遇到,但我不明白為什么它不能與整數一起工作。 由於我仍然接受仿制葯的概念,所以對這個問題的任何見解都會非常感激。 提前謝謝了!
您的SelectionSort
類是通用的。 在聲明並實例化其中一個時,應指定type參數:
SelectionSort<Integer> SS = new SelectionSort<Integer>(list, dataSize);
在Java 7中,您可以依靠類型推斷來縮短這一點:
SelectionSort<Integer> SS = new SelectionSort<>(list, dataSize);
SelectionSort SS = new SelectionSort(list, dataSize);//problem is here
應該
SelectionSort<Integer> SS = new SelectionSort<Integer>(list, dataSize);//no problem now
您的SelectionSort具有參數化類型(某些類型實現可比較)。 java.lang.Integer
實現了Comparable
。
這應該可以解決問題:
SelectionSort<Integer> ss = new SelectionSort<Integer>();
ss.sort(list, dataSize);
當您想要將參數傳遞給sort
方法時,您試圖將參數傳遞給不存在的構造函數。
在這里,我使用默認(no-arg)構造函數來實例化一個新的SelectionSort<Integer>
,將其分配給變量ss
,然后使用參數在該實例上調用sort
。
另請注意,如果您只需要實例來調用sort
,則可以跳過賦值:
new SelectionSort<Integer>().sort(list, dataSize);
SelectionSort SS = new SelectionSort(list, dataSize);
需要改為:
SelectionSort<Integer> SS = new SelectionSort<Integer>(list, dataSize);
您必須在創建對象時聲明參數化類型
除了已經涵蓋的泛型問題,我認為代碼混淆了構造函數和排序方法。 將失敗的行更改為:
SelectionSort<Integer> SS = new SelectionSort<Integer>();
SS.sort(list, dataSize);
代碼不顯示SelectionSort構造函數,只顯示一個sort方法,該方法需要傳遞給構造函數的參數。 錯誤消息與SelectionSort一致,只有編譯器默認提供無參數構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.