所以我正在编写一个通用邻接列表,我的代码没有编译错误,但是当我运行我的测试时,我得到了相同的运行时错误:
java.lang.ClassCastException: [[Ljava.lang.Object; cannot be cast to [[Lds.Graph.Edge;
at ds.TheAdjacencyMatrix.AdjacencyMatrix.<init>(AdjacencyMatrix.java:86)
at ds.TheAdjacencyMatrix.AdjacencyMatrix.<init>(AdjacencyMatrix.java:63)
at ds.TheAdjacencyMatrix.AdjacencyMatrix.<init>(AdjacencyMatrix.java:73)
at ds.Graph.Test.TheAdjacencyMatrixTest.testAddVertex(TheAdjacencyMatrixTest.java:33)
错误出现在我将 2d 对象数组转换为 E[][] 类型的行的构造函数中
邻接矩阵的相关代码是:
public class AdjacencyMatrix<T, E extends Edge>
implements AdjacencyMatrixInterface<T, E>, Graph<T, E> {
//~Constants----------------------------------------------
private static final int DEFAULT_SIZE = 10;
//~Data Fields--------------------------------------------
/**
* Int matrix that holds edge weights in weighted graphs.
* A 1 in a directed graph indicates an edge, a 0 indicates no edge.
*/
private E[][] matrix;
/**
* Array of elements contained in the graph.
* Elements correspond to the same indices as they do in the adjacency matrix of edges.
*
* i.e. matrix[4][5] is an edge from 4 to 5,
* elements[4] is the element at 4, elements[5] is the element at 5
*/
private T[] elements;
/**
* The maximum number of vertices in the adjacency matrix.
*/
private int size;
/**
* The current number of vertices in the graph.
*/
private int numVertices;
/**
* Indicates whether the graph is directed or not. True if directed, false otherwise.
*/
private boolean directed;
//~Constructors--------------------------------------------
/**
* Initializes the adjacency matrix to a size of 10.
* Which means there are 10 vertices in the graph.
*/
public AdjacencyMatrix() {
this(DEFAULT_SIZE);
}
/**
* Initializes the adjacency matrix to a size of 10. There will be 10 vertices in the graph.
*
* @param directed true if the graph is to be a directed graph, false otherwise.
*/
public AdjacencyMatrix(boolean directed) {
this();
this.directed = directed;
}
/**
* Initializes the adjacency matrix to a size of size.
* There will be a maximum size of *size* vertices in the graph
*
* @param size the size of the adjacency matrix.
*/
@SuppressWarnings("unchecked")
public AdjacencyMatrix(int size) {
matrix = (E[][]) new Object[size][size];
elements = (T[]) new Object[size];
this.size = size;
numVertices = 0;
directed = false;
}
Edge 类是一个抽象类,其代码在这里:
package ds.Graph;
/**
* An abstract Edge class which has methods
* getWeight()
* and
* setWeight(int weight).
* Used for a Graph data structure to abstract
* out the edges.
*
*
*
*/
public abstract class Edge implements Comparable<Edge> {
/**
* Sets the weight of the edge to the passed in weight.
*
* @param weight the weight of the edge.
*/
public abstract void setWeight(int weight);
/**
* Gets the weight of the edge.
*
* @return the edge weight.
*/
public abstract int getWeight();
}
编辑::
所以这是在运行时设置错误的代码行。IntEdge 只是一个继承自包含整数的 Edge 的对象。
AdjacencyMatrixInterface<String, IntEdge> matrix = new AdjacencyMatrix<String, IntEdge>(false);