What's the difference between unbounded wildcard type List<?> and raw type List?

Viewed 6812

Could you help me understand the difference between unbounded wildcard type List and raw type List?

List<?> b;    // unbounded wildcard type
List a;       // raw type


Along with this can anybody help me understand what is a bounded type parameter list?

List<E extends Number> c;
4 Answers

Both cases let us put into this variable any type of list:

List nothing1 = new ArrayList<String>();
List nothing2 = new ArrayList();
List nothing3 = new ArrayList<>();
List nothing4 = new ArrayList<Integer>();

List<?> wildcard1 = new ArrayList<String>();
List<?> wildcard2 = new ArrayList();
List<?> wildcard3 = new ArrayList<>();
List<?> wildcard4 = new ArrayList<Integer>();

But what elements can we put into this objects?

We can put only String into List<String>:

List<String> strings = new ArrayList<>();
strings.add("A new string");

We can put any object into List:

List nothing = new ArrayList<>();
nothing.add("A new string");
nothing.add(1);
nothing.add(new Object());

And we can't add anything (but for null) into List<?>! Because we use generic. And Java knows that it is typed List but doesn't know what type it is exact. And doesn't let us make a mistake.

Conclusion: List<?>, which is generic List, gives us type safety.

P.S. Never use raw types in your code.

Related