Casting an array of Objects into an array of my intended class

后端 未结 2 1442
情歌与酒
情歌与酒 2020-11-29 06:05

Just for review, can someone quickly explain what prevents this from working (on compile):

private HashSet data;

...

public DataObject[] getDataObjects( )
         


        
2条回答
  •  隐瞒了意图╮
    2020-11-29 06:13

    To ensure type safety when casting an array like you intended (DataObject[] dataArray = (DataObject[]) objectArray;), the JVM would have to inspect every single object in the array, so it's not actually a simple operation like a type cast. I think that's why you have to pass the array instance, which the toArray() operation then fills.

提交回复
热议问题