I was reading about Generics. And got into a situation:
List<Object> t1 = new ArrayList<>();
or
List<?> t2 = new ArrayList<>();
What is the difference in this 2 statements? Which one should be preferred?
I was reading about Generics. And got into a situation:
List<Object> t1 = new ArrayList<>();
or
List<?> t2 = new ArrayList<>();
What is the difference in this 2 statements? Which one should be preferred?
In List<Object> t1=new ArrayList<>();
, you are creating a List
object with generic type Object
. The empty diamond symbol on the right is inferred to be <Object>
.
On the bottom, with List<?>t2=new ArrayList<>();
This gives a compiler error:
Unexpected token: ?
This is because the Java compiler cannot infer what the generic type of your List
is. If you had not declared it with t2=new ArrayList<>();
and left the compiler to infer the type, you could have instantiated it with any generic (t2=new ArrayList<YourObjectTypeHere>()
).
So if you had to pick one, DONT do the second one as that gives a compile error.