首页 > 解决方案 > 为什么我的邻接列表给了我一个 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);
}

标签: javagenericsgraph

解决方案


你不能出于同样的原因,你不能做类似的事情

Object objArray = new String();
String strArray = ((String)new Object());

换句话说,每个类都是一个对象,但并非所有对象都是字符串。


推荐阅读