java - 为什么我的邻接列表给了我一个 ClassCast 异常?
问题描述
我正在使用邻接列表创建图表。(通过链表数组)。当我尝试创建和数组对象并将其转换回原始类型时,它因类转换异常而失败(通用数组的解决方法)。但是当我用原始类型替换它时,它可以工作。这是为什么 ?
public class Graph {
int vertices;
DoublyLinkedList<Integer>[] adjacencyList;
public Graph(int vertices) {
this.vertices = vertices;
// Below line throws an error : Class Cast Exception
**adjacencyList = (DoublyLinkedList<Integer>[]) new Object[vertices];** /
// Replace above line with this line and it works.
**adjacencyList = new DoublyLinkedList[vertices];**
for (int i = 0; i < vertices; i++) {
adjacencyList[i] = new DoublyLinkedList<>();
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(3);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 0);
}
解决方案
你不能出于同样的原因,你不能做类似的事情
Object objArray = new String();
String strArray = ((String)new Object());
换句话说,每个类都是一个对象,但并非所有对象都是字符串。
推荐阅读
- json - json:无法将字符串解组为 []main.KVU 类型的 Go 值
- node.js - 成功登录后如何将 JWT 与每个请求一起发送?
- database - Greenplum查询成本与查询分析不匹配
- ruby-on-rails - 防止用户在任何月份的某些日子编辑帖子
- java - 错误:缺少 JavaFX 运行时组件,需要使用 JDK 11 运行此应用程序
- html - Angularjs输入限制
- javascript - 如何从字符串 Vue.js 中删除 HTML 标签
- mysql - 如何按顶级父类别获取所有项目?
- intellij-idea - 这里不允许注释 IDEA
- java - P6间谍。如何检测中断语句?