Standard Java Use Format

When I need to create an ArrayList that should store strings, I do this -

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

In eclipse, when I omit the left or right of the above statement, I get a warning. Which brings me to my question, why does Java require / allow this? Don't we need to specify a common type, only one, only on one side?

+4
source share
3 answers

With Java 6 and earlier, what you typed on both sides is required.

However, starting with Java 7, you can use the "diamond operator" , empty angle brackets <>on the right side, and the compiler will select a type based on the type parameter on the left side.

ArrayList<String> whatwhat = new ArrayList<>();  // Java 7+
+4
source

, , , javac. , , Eclipse.

, Eclipse ( , dev Eclipse ), .

:
Eclipse, , .

enter image description here

+1

Well no. See that on the left you are using the generic type ArrayList, where on the right you are using the raw type ArrayList () ;, you can add whatwhat.add ("new :)", and Java will automatically warp the "new" to a new line. This is called autoboxing. While casting is not needed to extract the value from the list with the specified element type, since the compiler already knows the element type. The reason you get an error when you are not eligible is because it should

ArrayList<String> whatwhat = new ArrayList<>(); ... // some list that contains some strings
ArrayList<String> whatwhat = new ArrayList<String>(); ... // Legal since you used the raw type and lost all type checking
0
source

All Articles