Reputation: 14690
With Java 7 we could use the diamond operator:
List<String> list = new ArrayList<>();
Now I am seeing in some recent codes people dropping the diamond operator:
List<String> list = new ArrayList();
Is this a new feature added in more recent java versions (Java 8+) to drop the diamond operator? Or they are simply relying on the raw old ArrayList type (which just happens to work for backward compatibility reasons, and should be avoided)?
Upvotes: 4
Views: 2035
Reputation: 90
The correct syntax (for what you want) is:
List<String> l1=new ArrayList<>();
Omitting the diamond operator means an unqualified list, which (under the hood is the same, of course, but) will give you a compiler warning.
Using it unqualified works against the compile-time type-checking system, and is not in accordance with the variable you declare with the diamond operator, but it will compile (and work if you do it right). That's why you will get a warning.
Upvotes: 1
Reputation: 16457
In my opinion, you should not omit it if possible but it works.
Ommitting it means using the raw type. At runtime, this makes no difference as generics are erased at compiletime but you may get compiler warnings and/or linter warnings/errors/fails because the <Object>
type does not fit.
If you don't know the type or don't want to specify it, you can still use <? extends Object>
.
The problem is if you want to do something like this:
List<String>[] data=new List<String>[16];
This does not work because you cannot instantiate arrays of generics easily.
In that case, I would leave out the type interference and ignore(suppress) the (possible) compiler warnings.
@SuppressWarnings("unchecked")
List<String>[] data=new List[16];
But, as @vbezhenar mentioned in the comments:
It's better to avoid using arrays of generic types, just use something like
List<List<String>>
for that.
In general, List
s are easier to deal with than arrays, especially if you use generics.
Upvotes: 2