0

Is there any technically difference between below two lines?

List<com.xyz.Util> utilList = new ArrayList<com.xyz.Util>();
List<com.xyz.Util> utilList = new ArrayList<>();

I know the first one is typed and the second is not but technically both are same? This might be a trivial question but if you can explain in detail with example would be great. what are the advantages of using one over the other.

Stunner
  • 806
  • 1
  • 16
  • 35
  • 2
    It's the same, Intellij even alerts you to delete the unnecessary part. – Idos Aug 05 '21 at 18:13
  • The advantage is that you have to type less boilerplate code. I'd even use `var utilList = ArrayList()` as it is the shortest – Svetlin Zarev Aug 05 '21 at 18:15
  • It's not always the same everywhere. With your code, you're in the assignment context, so `<>` is inferred to be the same as the type argument given to `List`. But `new ArrayList<>().add(1);` and `new ArrayList().add(1);` won't behave the same way, the latter won't compile. So context matters. – ernest_k Aug 05 '21 at 18:18
  • @SvetlinZarev They're not exactly equivalent. `var utilList` would be `ArrayList`, not `List`. – shmosel Aug 05 '21 at 18:52
  • @shmosel Yes, it would be `ArrayList`, but this is irrelevant because `ArrayList` is `List`. – Svetlin Zarev Aug 05 '21 at 20:00
  • To add to that, when you say "the first one is typed and the second is not" this is technically _not_ correct. In the second case the type is _inferred_ which means your compiler is clever enough to figure out the type but that at runtime everything is still typed, as has been pointed out, it's just lest key strokes. – bschellekens Aug 05 '21 at 20:20
  • @SvetlinZarev Only because OP didn't post the next line, which goes `utilList = new LinkedList<>();`. – shmosel Aug 05 '21 at 21:37

0 Answers0