Java Generics:无法创建嵌套类的数组

时间:2022-09-29 21:20:25

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

我正在尝试将AVLTree实现转换为堆样式数组,并且在泛型方面存在一些问题:

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:

在行AVLNode [] bArray = new AVLNode [size];我收到以下错误:

"Cannot create a generic array of MyAVLTree.AVLNode"

“无法创建MyAVLTree.AVLNode的通用数组”

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

我不明白我做错了什么。有帮助吗?

2 个解决方案

#1


3  

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:

如果您希望实例化原始AVLNode [],您可以将类名限定为原始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.

您将获得警告,因为您通常会创建一个原始数组类型;但是这会编译。如果您不了解原始类型,请注意常见的事物,尽管当然您无法在Java中实例化非原始数组。

#2


0  

This sounds funny, but you can do such trick:

这听起来很有趣,但你可以这样做:

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

#1


3  

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:

如果您希望实例化原始AVLNode [],您可以将类名限定为原始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.

您将获得警告,因为您通常会创建一个原始数组类型;但是这会编译。如果您不了解原始类型,请注意常见的事物,尽管当然您无法在Java中实例化非原始数组。

#2


0  

This sounds funny, but you can do such trick:

这听起来很有趣,但你可以这样做:

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