5

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?

4
  • 1
    does this fix it: class AVLNode<K, E> implements Locator<K, E> ? Commented Nov 14, 2014 at 9:45
  • @vikingsteve this should be an answer Commented Nov 14, 2014 at 9:48
  • 2
    @vikingsteve You are just hiding the type variable. I highly doubt that is wanted. Commented Nov 14, 2014 at 9:50
  • Thanks vikingsteve, that was my first thought, but as Radiodef stated, it didn't really fix the problem. Commented Nov 14, 2014 at 9:55

2 Answers 2

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:

//                     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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it looks like it fixed the problem. I could swear I tried that and it didn't :)
0

This sounds funny, but you can do such trick:

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

2 Comments

Thanks, that seems to be another solution.
There is no point in using Array.newInstance() with a class hardcoded at compile time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.