Search code examples
javagenericssemantics

Is there a reason to double parametrize generics in Java?


Is there any reason to do this:

List<Integer> integers = new ArrayList<Integer>();

versus this:

List<Integer> integers = new ArrayList<>();

I've seen the first usage a few times, and it seems to provide no benefit, which begs the question: why use it?

I understand that the diamond operator (<>) is necessary to differentiate between new LinkedList() and new LinkedList<>(), just to be clear.


Solution

  • I've seen the first usage a few times, and it seems to provide no benefit, which begs the question: why use it?

    <> operator has been introduced only in JDK1.7, so you might have seen a legacy code, which used new ArrayList<Integer>() (without <> operator)

    Also, the support to the code (like <Integer>) without using <> operator still exists because of backward compatibility.

    So, the answer is you will not use it if your project uses JDK1.7 or later.