【发布时间】:2016-05-14 15:51:50
【问题描述】:
下面第一行注释的代码显示“无法将城市转换为 T”。所以在下一行,我将它转换为 T。 在主程序中编译方法“测试”后,它抛出此异常:“线程“主”中的异常 java.lang.ClassCastException:[Ljava.lang.Object; 无法转换为 [Lapi.xapi.City;”
谁能解释为什么会发生这种情况并在可能的情况下找到解决方案?
提前致谢。
顺便说一句,我需要访问 MyMap 类中 City 类的一些方法,如果真的没有其他方法,我只能使用强制转换。
public class MyMap <T extends City> extends DirectedGraph<City> {
public void add(T vertex) {
super.addVertex(vertex);
}
public void testing(T vertex) {
ArrayList<T> x = new ArrayList<>();
//x.add(super.vertices[0]);
x.add((T) super.vertices[0]);
}
}
----------------------------------------------- -------------------------------------------------------
信息更新:抱歉信息不足。
这是超类 DirectedGraph:
public class DirectedGraph<T>{
protected final int DEFAULT_CAPACITY=15;
protected T[] vertices;
protected double[][] edges;
protected int numVertices;
public DirectedGraph() {
this.vertices = (T[]) (new Object[DEFAULT_CAPACITY]);
this.edges = new double[DEFAULT_CAPACITY][DEFAULT_CAPACITY];
}
public void addVertex(T vertex) {
this.vertices[this.numVertices] = vertex;
this.numVertices++;
}
}
【问题讨论】:
-
super.vertices的类型是什么? -
请更正 - DirectedGraph
的构造函数应该是 public DirectedGraph()而不是public DiGraph()。此外,ArrayList<T>::addToRear(T t)方法不存在。听起来您可能想使用Deque<T>,它有一个addLast方法,可能正在做您想做的事情。 -
对不起。我只是在这里复制并粘贴并更改了一些代码以简化。 ArrayList
::addToRear(T t) 实际上存在,因为我使用的是我自己的 ArrayList 实现。现在我正在使用 Java 的 ArrayList 但问题仍然存在。感谢您的警告。
标签: java generics exception arraylist casting