问题描述
在处理通配符时,例如设置/添加一个通用项目到某个容器,是否建议使用类似这样的内容?
void add(List< ;? super T> someList,someitem){
someList.add(someItem);
}
当检索一个项目时,建议使用类似这样的内容
< T> void f1(List< ;? extends T> obj,T item){
obj.add(item);
}
这背后的原理是什么?什么时候才能知道我是否应该使用这个?
>
简而言之,当您想从对象获取信息时,请确保使用通配符进行扩展。
如果您想将信息放入对象中,请确保使用超级卡与通配符
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 ?
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
这篇关于Java通配符和泛型?超级T和?延伸T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!