【发布时间】:2018-04-21 16:32:08
【问题描述】:
我在将Car 的ArrayList 对象从最低MPG 排序到最大MPG 时遇到问题(使用SelectionSort 的修改版本)。这是我的代码:
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;
}
【问题讨论】:
-
你为什么不使用
Collections.sort()?你用谷歌搜索过排序示例吗? -
return myCars.stream().sorted(Comparators.comparing(Car::getMpg)).collect(Collectors.toList).
标签: java sorting object arraylist selection-sort