Collection Initialization

What is the difference between the following two statements when initializing an ArrayList ?

 ArrayList<String> a = new ArrayList<String>(); ArrayList<String> a = new ArrayList<>(); 
+4
source share
4 answers

Before Java 1.7, only one thing is allowed:

 ArrayList<String> a = new ArrayList<String>(); 

And in 1.7 the same thing is added, but in short: (all programmers are lazy)

 ArrayList<String> a = new ArrayList<>(); 
+13
source

The latter uses the alleged type introduced in Java 7. The syntax (known as the diamond operator) is illegal for collections prior to Java 1.7, so the former is used for these earlier versions.

The diamond operator reduces verbosity of the declaration.

+4
source

There is no difference. The second option (called the Diamond Operator) is a shortcut. The compiler will conclude that the generic ArrayList type parameter must be a string.

+3
source

The second option used the concept introduced in java 7 - the alleged types. Apart from this and assuming you are using java 7, the effect of the two calls should be the same. In earlier versions of Java, you cannot use the second version of your code.

0
source

Source: https://habr.com/ru/post/1490877/


All Articles