Java Generics: unable to create an array of nested class

I am trying to convert an AVLTree implementation to a heap style array, and I have 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; } } 

In the line AVLNode[] bArray = new AVLNode[size]; The following error appears:

"Unable to create shared array MyAVLTree.AVLNode"

I do not see what I am doing wrong. Any help?

+5
source share
2 answers

Inner classes capture type variables from an outer class, so you get an error.

If you want to instantiate raw AVLNode[] , you can qualify the class name as raw MyAVLTree :

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

You will get warnings, because usually you create a type of raw array; however this compiles. Be careful with the ordinary things that appear along with raw types if you don't know them, although of course you cannot create an array in Java that is not raw.

+3
source

It sounds funny, but you can do this trick:

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

Source: https://habr.com/ru/post/1206863/


All Articles