Reputation: 669
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
. On the other side, I have a class named Road
which has an ArrayList attribute of Vehicles. I want to order the list, named _vehicles
, using location
but in descending order, so I created this class into the Road class:
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
. But, when I execute the method _vehicles.sort(_vehicleComparator)
, I get this error:
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? Or am I missing something?
Thank you in advance
Upvotes: 5
Views: 15588
Reputation: 147154
You appear to be passing null
to List.sort
instead of your Comparator
. In this case, and some others, a null
Comparator
is interpreted as meaning use the elements' Comparable
interface.
Upvotes: 7