0

所以我正在编写一个通用邻接列表,我的代码没有编译错误,但是当我运行我的测试时,我得到了相同的运行时错误:

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);
4

5 回答 5

2

简单地将该行更改为

matrix = (E[][]) new Edge[size][size];

E在类内被擦除到其上限。E的上限Edge在这种情况下。所以它会尝试转换为Edge[][].

此外,您必须确保matrixelements不分别暴露于外部E[][]T[]因为它们并不是真正的那些类型。但只要你只在课堂内使用它们,就没有问题。

于 2013-05-20T09:12:32.413 回答
1

问题是 Object[][] 不是 Edge[][] 的实例。你不能像那样投射你的物体。

new Object[][] {} instanceof Edge[][] // => false

它的另一种方式 Object[][] 实际上是 Edge[][] 的超类

new Edge[][] {} instanceof Object[][] // => true

此外,根据Java 语言规范

数组类型的直接超类是 Object。每个数组类型都实现了接口 Cloneable 和 java.io.Serializable。

编辑:

此外,正如 Rahul Bobhate 指出的那样,最好使用Java Collections Framework,因为它旨在利用泛型。所有基于数组的解决方法都非常难看

于 2013-05-20T06:24:35.333 回答
0

这是不对的,您必须收到未经检查的强制转换警告:

matrix = (E[][]) new Object[size][size];
        elements = (T[]) new Object[size];

您需要显式传递数组实例,因为通用信息在运行时被擦除(这意味着在运行时正在执行的代码将是matrix = new Object[][]

你可以有这样的构造函数:

public class AdjacencyMatrix<T, E extends Edge> 
        implements AdjacencyMatrixInterface<T, E>, Graph<T, E> {
E[][] matrix;
T[] elements;
public AdjacencyMatrix(int size, E[][] matrix, T[] elements) {
        this.matrix = matrix;
        this.elements = elements;
   }
}
于 2013-05-20T06:25:37.187 回答
0

您不能将数组Object转换为E. 虽然它会编译,但它会ClassCastException在运行时导致。您只能转换兼容的引用类型。由于 array ofE和 array ofObject没有任何关系,JVM 将无法将 array ofObject转换为 array of E

您可以使用列表而不是数组。您可以将矩阵定义ListList如下:

private List<List<E>> matrix;
private List<T> elements;

matrix然后,您可以轻松地在构造函数中初始化:

public AdjacencyMatrix(int size) {

    matrix = new ArrayList<List<E>>(size);
    for(int i=0; i<size; i++)
    {
        t.add(new ArrayList<E>());
    }

    elements = new ArrayList<T>(size);

    this.size = size;
    numVertices = 0;
    directed = false;
}

然后,您可以访问列表中的元素,如下所示:

E e = matrix.get(0).get(1);

这将为您获取第一个列表中的第二个元素。

于 2013-05-20T06:57:32.650 回答
-1

原因是尽管 E 是 Object 的子类,但 E[] 不是 Object[] 的子类。数组具有扁平的类层次结构,因此不能相互转换。

[编辑]

我错了(谢谢评论)。实际上,数组有一个类型层次结构(参见http://etutorials.org/cert/java+certification/Chapter+6.+Object-oriented+Programming/6.5+Completing+the+Type+Hierarchy/)。正如正确指出的那样,您因此试图将超类型实例强制转换为子类型,这也不适用于任何其他 Java 对象。

于 2013-05-20T08:17:51.813 回答