Java wildcards and generics ? super T and ? extends T

最后都变了- 提交于 2019-12-06 12:29:46

问题


when dealing with wildcards such as setting/adding a generic item to a certain container is it suggested to use something like this?

void add(List<?  super T> someList,someitem){
    someList.add(someItem);
}

and when retrieving an item it is suggested to use something like this

 <T> void f1(List<? extends T> obj, T item) {
     obj.add(item);
}

What is the principle behind this? and when will I know if I should use this ?


回答1:


you should have a look at the explanation of PECS principle

What is PECS (Producer Extends Consumer Super)?

In short, when you want to get information from an object, make sure to use extends with the wild card.

And when you want to put information into an object, make sure to use super along with wild card



来源:https://stackoverflow.com/questions/12292752/java-wildcards-and-generics-super-t-and-extends-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!