我有一個Faculty成員的數組,我想使用插入排序它。 我在得到一個錯誤:用對象數組插入排序?
InsertionSort.insertionSortA(faculty, faculty.length);
錯誤說:「方法insertionSortA類插入排序不能用於給定類型;
要求:可比[],詮釋
發現:教師[],INT
我知道,這樣做是行不通的:
InsertionSort.insertionSortA((Comparable[]) faculty, faculty.length);
我知道,如果我有一個Integer []數組的工作,但我很困惑,爲什麼我的教師[] WOU ld不工作?
public class Tester {
public static void main(String[] args) {
InsertionSort insertionSort = new InsertionSort();
Education edu = new Education ("BA", "Business", 1);
Education edu2 = new Education ("BA", "Health Science", 1);
Education edu3 = new Education ("BA", "Computer Science", 1);
Faculty[] faculty = new Faculty[] {
new Faculty ("538", "Doe", "Jane", 'M', 1994,1,10,
"Assistant", edu),
new Faculty ("238", "Do", "John", 'F', 1994,6,1,
"Assistant", edu2),
new Faculty ("080", "White", "Snow", 'F', 1994,4,22,
"Full", edu3)
};
InsertionSort.insertionSortA(faculty, faculty.length);
}
}
public class InsertionSort {
public static void insertionSortA(Comparable[] theArray, int n) {
for (int unsorted = 1; unsorted < n; ++unsorted) {
Comparable nextItem = theArray[unsorted];
int loc = unsorted;
while ((loc > 0) &&(theArray[loc-1].compareTo(nextItem) > 0)) {
theArray[loc] = theArray[loc-1];
loc--;
} // end while
theArray[loc] = nextItem;
} // end for
} // end insertionSort
public static void insertionSortB(Comparable[] theArray, int n) {
for (int unsorted = 1; unsorted < n; ++unsorted) {
Comparable nextItem = theArray[unsorted];
int loc = unsorted;
while ((loc > 0) &&(theArray[loc-1].compareTo(nextItem) < 0)) {
theArray[loc] = theArray[loc-1];
loc--;
} // end while
theArray[loc] = nextItem;
} // end for
}
}