[英]Sorting an arraylist based on objects value in another arraylist in Java
[英]Java - Sorting Objects in an ArrayList<Car> based on MPG
我遇到問題(使用SelectionSort的修改版)對Car
對象的ArrayList
從最低MPG
到最大MPG
進行排序。 這是我的代碼:
public ArrayList<Car> getSortedByMPG(){
ArrayList<Car> bestMPG = new ArrayList<Car>();
bestMPG.addAll(myCars);
int smallestIndex;
Car smallest;
Car smallest1;
double smallestMPG;
double smallestMPG1;
for (int curIndex = 0; curIndex < bestMPG.size(); curIndex++) {
smallest = bestMPG.get(curIndex);
smallestMPG = smallest.getMPG();
smallestIndex = curIndex;
for (int i = curIndex + 1; i < bestMPG.size(); i++) {
smallest1 = bestMPG.get(i);
smallestMPG1 = smallest1.getMPG();
if (smallestMPG > smallestMPG1) {
smallest = bestMPG.get(i);
smallestIndex = i;
}
}
if (smallestIndex != curIndex) {
Car temp = bestMPG.get(curIndex);
bestMPG.set(curIndex, bestMPG.get(smallestIndex));
bestMPG.set(smallestIndex, temp);
}
}
return bestMPG;
}
此方法有一個測試器類,但是,我不想將其發布(以避免被拖累進行代碼轉儲)。 我已經處理了幾個小時,無法弄清楚為什么這段代碼沒有排序。 如果有人可以提供任何建議,將不勝感激。
編輯:謝謝大家的答復。 我意識到我之前沒有做適當的研究,但這就是為什么我來StackOverflow! 你們每天教我一些事情。
感謝Aomine,這是我解決的方法:
public ArrayList<Car> getSortedByMPG(){
ArrayList<Car> bestMPG = new ArrayList<Car>();
bestMPG.addAll(myCars);
Collections.sort(bestMPG, Comparator.comparingDouble(Car::getMPG));
return bestMPG;
}
排序列表的幾種方法之一是使用List.sort
方法並傳入比較器對象。 即:
bestMPG.sort(Comparator.comparingDouble(Car::getMpg));
那么您就可以返回bestMPG
。
如果我理解您的問題,則可以使用Collections.sort
ArrayList<Car> bestMPG = new ArrayList<Car>();
Collections.sort(bestMPG, new Comparator<Car>() {
public int compare(Car c1, Car c2) {
Double mpg1 = c1.getMpg();
Double mpg2 = c2.getMpg();
return mpg1.compareTo(mpg2);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.