【问题标题】:How to use ArrayList comparator with custom insertion sort method如何将 ArrayList 比较器与自定义插入排序方法一起使用
【发布时间】:2017-03-19 22:06:59
【问题描述】:

这是一个作业,我不能发布整个代码,但我真的需要了解我做错了什么。我敢肯定这是一个菜鸟的错误。:(

我必须构建一个自定义排序方法,对我的 arraylist 对象的特定属性进行排序。我创建了不同的比较器来处理我想要排序的对象中的不同元素。

*edit 添加更多代码

排序实用方法(需要参数):

public class CarManage{
    private ArrayList <Car> carList;    //carList defined

    public class Sorts {
        public static void sorts(Car[]carList, int size, Comparator <Car> someComparator)   //given parameters not allowed to modify
        {
            //sorts arrayList(carList) objects using an insertion sort algorithm.
        }
    }
}   //end class

我尝试调用 sort 方法来指定我需要排序的属性,但可惜它拒绝了第一个参数。

 public void sortByVinNumber(){
  VinNumComparator vnc = new VinNumComparator();//one of many comparators
  Sorts vncSort = new Sorts();

  for(int i = 0; i < carList.size(); i++){
        if(vnc.compare(carList.get(i-1), carList.get(i)) > 0){           
        vncSort.sorts(Car[]carList, 2, vnc);//not working here rejects first parameter
        ///vncSort.sorts(carList,2,vnc)///doesn't work
        }
    }
 } 

我不确定它为什么不接受我的参数?会不会是pass-reference错误?还是我可能调用错误的方法?

【问题讨论】:

  • 参数列表中不要把Car[]放在carList前面。只有在声明变量时才对变量这样做
  • 我试过这个。然后整个排序方法被拒绝,并给我错误“排序类型中的方法排序(Car[],int,Comparator)不适用对于参数 (ArrayList, int, VinNumberComparator)"
  • 你在哪里定义carList?向我们展示那条线。该方法需要 ArrayList 而不是数组。
  • Comparable&lt;Car&gt; 接口实现你的Car 类并声明compareTo(Car anotherCar) 的覆盖方法怎么样?在 compareTo 中,您可以声明自己的比较 Car 实例的逻辑。然后你可以使用简单的Collections.sort( carArrayList )
  • @C.T 不,当您呼叫sorts 时,不要在carList 之前输入Car[]。只有在声明对象时才这样做

标签: java sorting arraylist comparator


【解决方案1】:

你需要像这样调用方法:

vncSort.sorts(carList, 2, vnc);

此外,您似乎将数组与 ArrayList 混淆了。一个汽车数组将是Car[]ArrayList&lt;Car&gt; 是一个 List,它接受并产生 Car 类型。之所以称为ArrayList,是因为它在内部由一个数组支持。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2016-12-01
    相关资源
    最近更新 更多