How can I add to List<? extends Number> data structures?

前端 未结 6 1131
暗喜
暗喜 2020-11-22 02:19

I have a List which is declared like this :

 List foo3 = new ArrayList();

I tried to add 3 to foo3.

6条回答
  •  清歌不尽
    2020-11-22 03:13

    You can't (without unsafe casts). You can only read from them.

    The problem is that you don't know what exactly the list is a list of. It could be a list of any subclass of Number, so when you try to put an element into it, you don't know that the element actually fits into the list.

    For example the List might be a list of Bytes, so it would be an error to put a Float into it.

提交回复
热议问题