我應該創建一個方法,該方法使用有界泛型類型的ArrayList,並使用以下算法基於對象的體積對它進行排序(我必須完全按照它進行)。綁定應該只允許任何形狀的對象和子類:我的recursiveSort()方法不工作? (泛型)
if the list size is <= 1
return the list
select a middle element from the list and remove it
create two lists leftList and rightList
for each element in the list
if element is less than the middle element then add element to the rightList
else add element to leftList
return the combination of recursiveSort(leftList), middle element, and recursiveSort(rightList)
我Shape類是單純只用getVolume()方法的接口在我的其他類(球形,橢圓等)覆蓋此方法
這裏是我的遞歸代碼(在另一個類,做其他方法,如發現最小值和最大值):
public class ShapeUtilities {
public static <T extends Shape> Collection<? extends T> recursiveSort(ArrayList<T> list) {
if (list.size() <= 1) {
return list;
}
int middleIndex = list.size()/2;
T middleElement = list.get(middleIndex);
list.remove(middleIndex);
ArrayList<T> leftList = new ArrayList<T>();
ArrayList<T> rightList = new ArrayList<T>();
for (T item : list) {
if (item.getVolume() < middleIndex) {
rightList.add(item);
} else {
leftList.add(item);
}
}
ArrayList<? extends Shape> combination = new ArrayList<T>();
combination.addAll(recursiveSort(leftList));
combination.add(middleElement);
combination.addAll(recursiveSort(rightList));
return combination;
我怎樣才能返回「recursiveSort(leftList)的組合,中間元素,並recursiveSort(rightList )「?它不會添加到我創建的ArrayList中,只是返回中間元素而不是全部三個元素。
(這是快速排序) – njzk2
(你錯過在你的'rightList'上調用'recursiveSort') – njzk2
'list.get(i).getVolume()
njzk2