我在对 Car
对象的 ArrayList
从最低 MPG
到最大 进行排序时遇到问题(使用 SelectionSort 的修改版本) >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 的原因!你们每天都教我一些东西。
这是我解决这个问题的方法,感谢青峰:
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
。
关于Java - 基于 MPG 对 ArrayList<Car> 中的对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189004/