首先,我知道有些人已经问过类似的问题,但我不确定这是否和他们问的一样。
我有一个名为的类Vehicle,它有一个名为location. 另一方面,我有一个名为的类Road,它具有 Vehicles 的 ArrayList 属性。我想_vehicles使用location但按降序排列命名列表,所以我将这个类创建到 Road 类中:
class CompareVehicles implements Comparator<Vehicle> {
@Override
public int compare(Vehicle o1, Vehicle o2) {
if (o1.getLocation() < o2.getLocation()) return 1;
if (o1.getLocation() > o2.getLocation()) return -1;
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
以及一个名为 的属性_vehicleComparator,其类型为CompareVehicles。但是,当我执行该方法时_vehicles.sort(_vehicleComparator),出现此错误:
java.lang.ClassCastException: class simulator.model.Vehicle cannot be cast to class java.lang.Comparable (simulator.model.Vehicle is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader …Run Code Online (Sandbox Code Playgroud)