How do I get an inner class to inherit enclosing class' generic type?

后端 未结 5 1415
旧时难觅i
旧时难觅i 2020-12-14 01:44

I\'m using Java 6.

I\'m having trouble getting my inner class to use the same generic class as its enclosing class. Currently I have

public class          


        
5条回答
  •  Happy的楠姐
    2020-12-14 02:04

    As to the compile error for generic array creation when you remove the T from the inner class:

    Because it's a non-static inner class, it's within the scope of the outer class's type parameter. Which means that it is implicitly also parameterized by its outer class's type parameter

    So when you write TSTNode it basically means TernarySearchTree.TSTNode (the T here is the outer T). So TSTNode is still a generic type (even though you don't see any brackets explicitly), and creating an array of a generic type fails.

    You can refer to the raw type of TSTNode by manually qualifying the name: TernarySearchTree.TSTNode.

    So new TernarySearchTree.TSTNode[4] is the answer.

    You will get an unchecked warning, which you can ignore (it is something you have to live with with arrays of generic types)

    P.S. removing the type parameter from the inner class is almost certainly the right choice, as non-static inner classes in Java implicitly have a reference to an instance of the outer class. So it is already parameterized with the outer T. If you simply want to use the same T, don't declare another one.

提交回复
热议问题