2

Maybe it is silly question: Let say I have

abstract class A<T> {
  List<Wrapper<T>> doStuff()
}

And I have class B extends A<String> and class C extends A<Integer>

Now I want to have:

List<A> aces = list with instances of B and C;

List<Wrapper> wrapperedItems = flattened list of lists returned from doStuff() on all items in aces

At this point I don't care what type is within Wrapper. And my question is: shall I use somewhere <?> or can I skip it? What is the difference?

kkonrad
  • 1,262
  • 13
  • 32
  • possible duplicate of [difference between List and List>](http://stackoverflow.com/questions/14983489/difference-between-list-and-list) – Louis Wasserman Mar 19 '14 at 16:40
  • also http://stackoverflow.com/questions/7360594/whats-the-difference-between-raw-types-unbounded-wild-cards-and-using-object-i – Louis Wasserman Mar 19 '14 at 16:40

1 Answers1

1

If you use List<Wrapper<?>>, you will be able to get objects out of the list, but you will not be able to add new items. The wildcard essentially correcponds to a type that is different from any other type, including other wildcards.

If you use List<Wrapper>, you will be able to both get list items and add new ones, but the onus is now up to you to guard for improper type casts.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40