Java Generics: Cannot create an array of a nested class

浪尽此生 提交于 2019-12-30 19:53:11

问题


I'm trying to convert an AVLTree implementation into a heap style array and am having some problems with generics:

public class MyAVLTree<K extends Comparable<? super K>, E> implements
    OrderedDictionary<K, E> {

    class AVLNode implements Locator<K, E>{
        // ...
    }

    // ....

    public Locator<K,E> [] toBSTArray() {
        AVLNode[] bArray = new AVLNode[size];
        makeArray(root, 0, bArray);  // recursion
        return bArray;
    }
}

At the line AVLNode[] bArray = new AVLNode[size]; I get the following error:

"Cannot create a generic array of MyAVLTree.AVLNode"

I don't see what I'm doing wrong. Any help?


回答1:


Inner classes capture the type variables from an outer class so this is why you get the error.

If you wish to instantiate a raw AVLNode[] you may qualify the class name as raw MyAVLTree:

//                     vvvvvvvvv
AVLNode[] bArray = new MyAVLTree.AVLNode[size];

You will get warnings as you normally would creating a raw array type; however this will compile. Be advised the usual things that come along with raw types if you don't know them, although of course you cannot instantiate an array in Java that is not raw.




回答2:


This sounds funny, but you can do such trick:

AVLNode[] bArray = (AVLNode[]) Array.newInstance(AVLNode.class, size);


来源:https://stackoverflow.com/questions/26926920/java-generics-cannot-create-an-array-of-a-nested-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!