Creating Arrays of Generic Types in Java

前端 未结 5 1924
半阙折子戏
半阙折子戏 2021-01-18 09:11

So I know that you cannot \"easily\" create an array of a generic type in Java (but you can create collections). I recently ran across a situation where I needed a 2 dimens

5条回答
  •  太阳男子
    2021-01-18 10:13

    This will allow it to work (along with an unchecked cast, which is normal for this situation since you want to have a variable that is the array of a generic type). The solution is realizing that just Foo refers to the parameterized class Outer.Foo, since you are inside the scope of Outer; and that to get the actual raw class, you need to explicitly qualify it as Outer.Foo:

    foo = (Foo[][])new Outer.Foo[width][height];
    

提交回复
热议问题