无法在Java中创建通用类的对象数组

时间:2014-06-13 20:10:25

标签: java object generics

在Node Class构造函数中,我尝试初始化childArraydataArray,这些对象基于Generic类本身。

private class Node<type extends Comparable<type>> {
        public Node<type>[] childArray;
        public DataItem<type>[] dataArray;
        public int dataCount; //No. of data elements in the node
        public int childCount; //No. of child elements under it
        public Node<type> parent;
        private static final int ORDER = 4;

        public Node() {

            childArray = (Node<type>[]) new Object[ORDER];
            dataArray = (DataItem<type>[]) new Object[ORDER - 1];
            dataCount = 0;
            childCount = 0;
        }
}

我在尝试编译时遇到以下错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LTree234$Node;
    at Tree234$Node.<init>(Tree234.java:37)
    at Tree234.<init>(Tree234.java:149)
    at Tree234.main(Tree234.java:266)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

完整的代码可在以下位置找到: https://gist.github.com/stirredo/2a40d48021a8b9e14959

我如何克服这个问题?

我知道在我的问题中发现异常有很多问题但是我无法将它们应用到我的问题中。

2 个答案:

答案 0 :(得分:1)

您试图将Object[]投放到Node[],而Object[]曾是Node[]。大概是你把演员阵容放在上面因为childArray = new Object[ORDER]在编译时给你incompatible types。同样,ClassCastException是由于两个未能解决为&#34;兼容&#34; state(在运行时)。

所以你希望childArray = new Node<T>[ORDER];also not possible。简而言之,您应该使用某种形式的Collection

class Node<T extends Comparable<T>> {
  private Collection<Node<T>> children;
}

答案 1 :(得分:1)

childArray = (Node<type>[])new Node[ORDER];

childArray = (Node<type>[])new Node<?>[ORDER];
相关问题