【问题标题】:Java - Sorting Objects in an ArrayList<Car> based on MPGJava - 基于 MPG 对 ArrayList<Car> 中的对象进行排序
【发布时间】:2018-04-21 16:32:08
【问题描述】:

我在将CarArrayList 对象从最低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


【解决方案1】:

对列表进行排序的几种方法之一是使用List.sort 方法并传入一个比较器对象。即:

bestMPG.sort(Comparator.comparingDouble(Car::getMpg));

那么你可以直接返回bestMPG

【讨论】:

  • 是的。我想这是我想到的第一件事。将更新:-)。
【解决方案2】:

如果我理解您的问题,您可以使用 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);
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 2014-11-09
    • 2015-12-13
    • 2011-05-03
    • 2017-12-12
    • 2015-10-06
    • 2012-04-26
    • 1970-01-01
    相关资源
    最近更新 更多