【问题标题】:How do I sort the items in the ArrayList and change the places of items in another array depending on order in the ArrayList?如何对 ArrayList 中的项目进行排序并根据 ArrayList 中的顺序更改另一个数组中项目的位置?
【发布时间】:2015-05-18 02:08:05
【问题描述】:

有一个车辆对象的 ArrayList,使用了很多次。每个对象都有一个 id 和它被使用的次数。

ArrayList<Object> usedVehicles = new ArrayList();

还有一个数组,保存所有车辆的id。

int[] vehicleIDs = database.getVehicleIds();

我需要根据使用次数对vehicleIDs数组中的元素进行排序,显然从未使用过的车辆必须排在第一位。

我想我可以用比较器对 ArrayList 中的车辆对象进行排序:

public class CustomComparator implements Comparator<MyObject> {
  @Override
  public int compare(Vehicle vehicle1, Vehicle vehicle1) {
     return vehicle1.getTheNumberOfTimesUsed().compareTo(vehicle2.getTheNumberOfTimesUsed()());
    }
}  

但是,我不知道如何根据 ArrayList 中的顺序更改 vehicleIDs 数组中项目的位置。此外,从未使用过的车辆必须先来。

【问题讨论】:

  • 不可能只从排序的 ArrayList 创建一个新数组吗?
  • 不,不是。正如我所说,只有使用了一定次数的车辆才在 ArrayList 中。并且从未使用过的车辆在更新后必须按照vehicleIDs数组中的项目顺序排在第一位。我们不允许将这些未使用的车辆添加到 ArrayList。所以,我仍然需要根据排序后的 Arraylist 更新 vehicleIDs 数组。

标签: java arrays object arraylist comparator


【解决方案1】:

在java中你无法直接改变数组中元素的顺序。

但是,您可以根据排序后的 ArrayList 创建一个新数组(例如 newVehicleIDs ),并将您的 vehicleIDs 数组的值替换为新创建的数组(vehicleIDs = newVehicleIDs;)。

【讨论】:

    【解决方案2】:

    ArrayList 包含用户定义的对象。通过使用 Collections.sort() 方法,您可以对 ArrayList 进行排序。

    Collections.sort(list,new CompareVehicleIds())
    

    您必须传递包含您的排序逻辑的 Comparator 对象。

    class CompareVehicleIds implements Comparator<Object>{
    
             @Override
              public int compare(Vehicle vehicle1, Vehicle vehicle1) {
                 return vehicle1.getTheNumberOfTimesUsed().compareTo(vehicle2.getTheNumberOfTimesUsed()());
                }
            }
    

    希望我对您有所帮助。

    【讨论】:

      【解决方案3】:

      使用您将用于正常排序的排序算法,但将两个数组都作为参数并使用一个进行比较。您必须对两者进行排序才能使其正常工作。当然,如果 ArrayList 中没有指定 ID 的条目,则它必须排在第一位,因为它显然没有被使用过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-13
        • 2020-01-03
        • 1970-01-01
        • 1970-01-01
        • 2022-01-06
        • 1970-01-01
        • 2019-04-25
        • 1970-01-01
        相关资源
        最近更新 更多