5

When I need to create an ArrayList that needs to store Strings, I do this -

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

In eclipse, when i omit <String> from left or right of the above statement, i get a warning. Which brings me to my question, why does Java require/allow this? Shouldn't we be required to state the Generic type just one, on one side only?

1
  • if you want to know the logically reason why, read my answer. Commented Jul 11, 2015 at 1:49

3 Answers 3

5

With Java 6 and before, what you have 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 infer the type based on the type parameter on the left side.

ArrayList<String> whatwhat = new ArrayList<>();  // Java 7+
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Eclipse needs a spanking maybe.
Actually, i take that back about eclipse. Using diamond operator on right will not trigger eclipse warnings. Good stuff!
1

As you can see that there is no error, so you can be sure that this is allowed by javac. Now, you are getting warning, so this is related to feature provided by Eclipse.

In fact, Eclipse provides these kind of features to warn (or give error, if dev has configured Eclipse for the same) that you are using old conventions, and should update.

For solution:
You may want to change your Eclipse setting as below and your warning should be gone.

enter image description here

Comments

0

Well no. See is that on the left hand side, you are using the generic type ArrayList where on the right side you are using the raw type ArrayList(); . You can add a whatwhat.add("new:); and Java will automatically warp "new" into new String. This is called autoboxing. While casting is not needed to retrieve a value from a list with a specified element type, because the compiler already knows the element type. The reason you are getting an error when you don’t have on the right, is because it must

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

2 Comments

I am actually not getting an error. Its just an IDE warning regarding the correct use of Generics. Once i used diamond operator on the right, it fixes both my problems which was repeating generic definition and IDE warning.
yeah it wouldn’t give a error either way. I was just explaining the warning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.