Java templates and generics? super T and? extends T

when using wildcards like setting / adding a shared item to a specific container, is it suggested to use something like this?

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

      

and when retrieving an element, 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 i know if i should use it?

+1


source to share


1 answer


you should take a look at the explanation of the PECS principle

What is PECS (Producer Extend Consumer Super)?



In short, when you want to get information from an object, be sure to use wild card extensions.

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

+2


source







All Articles