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

前端 未结 6 966
暗喜
暗喜 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:18

    It has been confusing to me even though I read answers here, until I found the comment by Pavel Minaev:

    Note that List < ? extends Number > does not mean "list of objects of different types, all of which extend Number". It means "list of objects of a single type which extends Number"

    After this I was able to understand BertF awesome explanation. List < ? extends Number > means ? could be of any type extending Number(Integer, Double, etc) and its not clearified in declaration ( List < ? extends Number > list ) that which of them it is, so when u wanna use add method its not known if the input is of the same type or not; what is the type at all?

    So the elements of List < ? extends Number > could only be set when constructing.

    Also note this: When we're using templates we are telling the compiler what type we're messing with. T for example holds that type for us, but not ? does the same

    I gotta say.. This is one of the dirty ones to explain/learn

提交回复
热议问题