[英]Class cannot be cast to java.lang.Comparable
First of all, I know some people has already asked similar questions, but I'm not sure if this is the same as what they asked.首先,我知道有些人已经问过类似的问题,但我不确定这是否和他们问的一样。
I have a class named Vehicle
which has an attribute named location
.我有一个名为
Vehicle
的类,它有一个名为location
的属性。 On the other side, I have a class named Road
which has an ArrayList attribute of Vehicles.另一方面,我有一个名为
Road
的类,它有一个 Vehicles 的 ArrayList 属性。 I want to order the list, named _vehicles
, using location
but in descending order, so I created this class into the Road class:我想使用
location
但按降序对名为_vehicles
的列表进行排序,因此我将此类创建到 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;
}
}
And an attribute named _vehicleComparator
which its type is CompareVehicles
.还有一个名为
_vehicleComparator
的属性,它的类型是CompareVehicles
。 But, when I execute the method _vehicles.sort(_vehicleComparator)
, I get this error:但是,当我执行方法
_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 'bootstrap')
at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.base/java.util.Arrays.sort(Arrays.java:1316)
at java.base/java.util.Arrays.sort(Arrays.java:1510)
at java.base/java.util.ArrayList.sort(ArrayList.java:1717)
at simulator.model.Road.advance(Road.java:115)
at simulator.model.TrafficSimulator.advance(TrafficSimulator.java:44)
at simulator.control.Controller.run(Controller.java:54)
at simulator.launcher.Main.startBatchMode(Main.java:136)
at simulator.launcher.Main.start(Main.java:144)
at simulator.launcher.Main.main(Main.java:156)
Should Vehicle
implement the Comparable
interface, even if I'm using a Comparator?即使我使用的是比较器,
Vehicle
是否应该实现Comparable
接口? Or am I missing something?或者我错过了什么?
Thank you in advance先感谢您
You appear to be passing null
to List.sort
instead of your Comparator
.您似乎将
null
传递给List.sort
而不是您的Comparator
。 In this case, and some others, a null
Comparator
is interpreted as meaning use the elements' Comparable
interface.在这种情况下和其他一些情况下,
null
Comparator
被解释为意味着使用元素的Comparable
接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.