-1

What's the difference between the following lines:

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

I just started learning about collections and data structures from the HeadFirstJava book and am a bit confused since I see people use all three of the examples above while researching.

vader
  • 45
  • 1
  • 8

1 Answers1

4

The first and second line use raw types.

A raw type is a type that is used without type parameters, even though the base class has a type argument.

Raw types exist only for backwards compatibility with ancient (pre-Java 5) code and should never be used in new code at all. The rules about raw types are weird and unintuitive.

The third one is correct, but can be written in a shorter way like this:

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

This one will let the compiler "guess" what is meant to go into the <>.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614