but of which type was the ArrayList created?
Type parameters are just constraints applied at compile time, but type erasure replaces all occurrences of the type parameter by its erasure (in your case, Object
). So, if you're asking about the runtime type, it will be a plain ArrayList
(which you can think of as ArrayList<Object>
).
is it good to use the diamond-operator with wildcards? If YES then
WHERE???
No. When you use a diamond operator to create a new object of a generic class, it means you don't want to be redundant on the type parameter. It should not be combined with a wildcard-declared variable, which does not have a concrete type parameter.
To summarize, you should never write:
List<?> unknownList = new ArrayList<>();
You should only use the wild card <?>
when the type really does not matter. In particular, don't use the wild card if you want to add items to the list, because adding items means you know what type to add.
It is likely to be used as a parameter of a method for instance, when you don't access the value and just pass the list on, or where you just access the list items as plain Objects.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…