![](/img/trans.png)
[英]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.