[英]Exception in thread "main" java.lang.ClassCastException: proj.Car cannot be cast to java.lang.Comparable
I'm trying create something like this tutorial on creating a graph and I'm coming across an error: Exception in thread "main" java.lang.ClassCastException: proj.Car cannot be cast to java.lang.Comparable
.我正在尝试创建类似于创建图形的本教程的内容,但遇到了一个错误: Exception in thread "main" java.lang.ClassCastException: proj.Car cannot be cast to java.lang.Comparable
。
Car class汽车class
Integer id;
String model;
String brand;
float price;
Cars class (both have been instantiated already):汽车 class (两者都已实例化):
TreeMap<Integer, Car> m;
TreeMap<Car, LinkedList<Car>> adjList;
Main:主要的:
for(Map.Entry<Integer, Car> entry : a.m.entrySet()){
Car val = entry.getValue();
LinkedList<Car> list = new LinkedList<Car>();
a.adjList.put(val, list);
}
This creates an adjList
for every Car object in m
but the problem is the error.这将为m
中的每辆汽车 object 创建一个adjList
,但问题是错误。 I've tried making sure the entered variables are of the same type by using instanceof
and it returns true.我尝试使用instanceof
确保输入的变量属于同一类型,并且它返回 true。 So i'm not sure where the error comes from.所以我不确定错误来自哪里。
TreeMap is a SortedMap implementation and it requires its keys to implement the Comparable interface in order to sort the keys. TreeMap 是一个 SortedMap 实现,它需要它的键来实现 Comparable 接口以便对键进行排序。
So I assume Car does not implement Comparable.所以我假设 Car 没有实现 Comparable。 If you add this implementation, you'll be fine.如果你添加这个实现,你会没事的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.