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 ?

KyelJmD
  • 4,682
  • 9
  • 54
  • 77
  • possible duplicate of [What's the purpose behind wildcards and how are they different from generics?](http://stackoverflow.com/questions/2922811/whats-the-purpose-behind-wildcards-and-how-are-they-different-from-generics) – Thilo Sep 06 '12 at 04:00
  • also, you could remember a key "Producer Extends Consumer Super" from [Effective Java](http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683) – cat916 Sep 06 '12 at 04:03
  • What's the difference supposed to be between these snippets? I see some typos in the first one. – Paul Bellora Sep 06 '12 at 04:03
  • @PaulBellora Ooops, I've updated it. – KyelJmD Sep 06 '12 at 04:06
  • How is this an exact duplicate? – KyelJmD Sep 06 '12 at 05:04

1 Answers1

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

Community
  • 1
  • 1
user1676688
  • 414
  • 4
  • 15