Java wildcards and generics ? super T and ? extends T
Asked Answered
S

1

1

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 ?

Salena answered 6/9, 2012 at 3:57 Comment(5)
possible duplicate of What's the purpose behind wildcards and how are they different from generics?Enoch
also, you could remember a key "Producer Extends Consumer Super" from Effective JavaFireside
What's the difference supposed to be between these snippets? I see some typos in the first one.Indochina
@PaulBellora Ooops, I've updated it.Salena
How is this an exact duplicate?Salena
C
2

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

Cypsela answered 3/10, 2012 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.