Creating Arrays of Generic Types in Java

前端 未结 5 1928
半阙折子戏
半阙折子戏 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 09:56

    What you're doing is safe because you're controlling the unexposed map. You should probably make it private though and not protected, otherwise extending classes could incorrectly manipulate it. You can get rid of the compiler warning by casting into a runtime check, like this:

    this.map = BaseCell[][].class.cast(Array.newInstance(BaseCell.class,
            new int[] { width, height }));
    

    Then if at some later point the code is potentially changed in an incompatible way that the compiler warning would mask out, it'll at least break early with a runtime exception at the construction of your map. Keep in mind of course that Generics are simply erased at compile time.

提交回复
热议问题