4

What's the difference between the two declarations?

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

They work, but the second one returns a warning. I don't understand why.

I understand the difference between ArrayList<String> arr and ArrayList arr, the first enables a type checking control. But what about new ArrayList<String>() and new ArrayList()? Is there any difference at implementation level? What do I lose in terms of controls?

zer0uno
  • 7,521
  • 13
  • 57
  • 86
  • 9
    It detects the type if you use the `<>` diamond operator, like `List strings = new ArrayList<>();` – GhostCat May 13 '16 at 13:24

3 Answers3

3

In Java 7 it can detect the type automatically, but you'll need to use the Diamond Operator:

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

It's basically syntactic sugar for the first line. Without the diamond operator, it's a raw type (a non-parameterized generic type). Raw types exist for compatibility with older Java versions that don't support generics but will cause warnings when used.

kapex
  • 28,903
  • 6
  • 107
  • 121
  • 2
    Even though this is true, it doesn't answer the question asked: "What is the difference between `ArrayList arr = new ArrayList()` and `ArrayList arr = new ArrayList();`?".. – Kevin Cruijssen May 13 '16 at 13:30
  • @kapep I got it, but I don't understand yet what I lose, in terms of compiler checkings, coding `ArrayList arr = new ArrayList();`. I mean, if I code in this way doing `arr.add(arr.get(0))` dosn't return an error. – zer0uno May 14 '16 at 10:55
1

As mentioned before, this can be resolved using the <> diamond operator.

But there are reasons why this is so. You have to keep in mind that generics where added after the collection classes. And the idea was they generics should not break existing source code. Sun didn't want that customers would all of a sudden fail when compiling tons and tons of existing code using un-generified lists ...

So the java compilers had to accept code like ... = new ArrayList(). But the point is, that this kind of declaration creates a so called "raw type".

And if possible, you should never ever use raw types. And that is why eclipse and javac give you warnings - to remind you to never create raw types.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You need to know that at runtime, all generics are erased, so that all ArrayLists are of the same type, no matter what you put into your < >.

So while the second line is possible (for historic reasons, before generics were possible), it should be avoided because it obfuscates the types.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142