Java generics and Array's

前端 未结 5 1454
长发绾君心
长发绾君心 2020-12-22 08:34

The following snippet makes sense yet when I run this against my unit test.. I get a ClassCastException (Object can\'t be cast to String) on the line marked with \'>>>>\'.

5条回答
  •  春和景丽
    2020-12-22 09:18

    you're casting Object to String, IOW, a super class to the inherited one. It is always prohibited. As AlexR suggested, make use of Arrays.newInstance(). But in that case you would have to pass a class of your object as here:

    ArrayUtils.append(array, "b", String.class);
    

    I suggest you not to try implementing this standard behaviour of dynamically extended array : it has been already implemented in ArrayList class. You can checkout the source to learn how it is dealing with generics.

提交回复
热议问题