0

What is the difference between

List<String> list = new ArrayList();

and

List<String> list = new ArrayList<>();

?

In the first case, the IDE highlights it and says "Unchecked assignment", but they seem to behave exactly the same.

Kidades
  • 600
  • 2
  • 9
  • 26
  • `List<>` is a generic type, and generic types should always be used with diamond operator. You use it as raw type, so thats why IDE complains. – callOfCode Feb 25 '16 at 22:09

2 Answers2

2

The type of each entry in the ArrayList has not been specified, only the List, hence why the Unchecked assignment warning. You should explicitly state it in one of two ways...

List<String> list = new ArrayList<String>();

Or, you can abbreviate that now (since Java 7) to...

List<String> list = new ArrayList<>();

...and the compiler will then be able to implicitly pick up the type from the List's type designation.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
  • 2
    Yep. See See: https://docs.oracle.com/javase/8/docs/technotes/guides/language/type-inference-generic-instance-creation.html – Joshua Davis Feb 25 '16 at 22:19
1

No difference, java compiler could figure out the type, but better add the inferred type argument:

List<String> list = new ArrayList<String>();
dcai
  • 2,557
  • 3
  • 20
  • 37
  • IDEA will complain about that too. He will suggest new ArrayList<>() – Joshua Davis Feb 25 '16 at 22:18
  • There is a difference. The first one (new ArrayList();) is wrong. The second (new ArrayList<>();) is correct. ArrayList() would also be fine, but the first one is definitely incorrectly defined. – ManoDestra Feb 26 '16 at 14:29