Java - 基于 MPG 对 ArrayList<Car> 中的对象进行排序

标签 java sorting object arraylist selection-sort

我在对 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/

相关文章:

java - 未能使用 User 对象作为参数?在 Java 泛型中扩展 User

sorting - 根据过滤条件对Elasticsearch结果集进行排序

algorithm - 剖析合并排序例程

javascript - 动态更改多段线颜色

java - Scala 重载方法

java - 调用init方法失败;嵌套异常是 java.lang.IllegalArgumentException : 'sessionFactory' or 'hibernateTemplate' is required

java - RecyclerView 中的定位是如何工作的?

c# - 将这个简单的代码从 javascript 转换为 c#

javascript - 使用 React 开发时深度复制对象

php - 在 PHP 类中使用全局 DB 变量