0

I'm having trouble understanding the correct ways to declare a linked list. I read online that all of the following syntaxes are correct:

LinkedList<Integer> list1 = new LinkedList<Integer>();
List<Integer> list2 = new LinkedList<Integer>();

Why is this the case? Are there any differences between them, or will they all create the same list?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Briar
  • 177
  • 1
  • 2
  • 8
  • 1
    both are wrong: `new LinkedList()` should not compile with Java - it would be `new LinkedList()` or even `new LinkedList<>()` (diamond notation, type not needed to be repeated); and a third alternative, assuming the 2 are corrected: `var list3 = LinkedList();` (this needs the type) – user16320675 Mar 23 '23 at 17:36
  • @user16320675 While all what you said is true I suspect that main point of question was confusion between `List` vs `LinkedList`, so I edited the incorrect `` part. Hope you don't mind. – Pshemo Mar 23 '23 at 17:48
  • 1
    The latter (interface) is to prefer! ...but sometimes if you need some implementation specific "things", you better go with first (concrete class..instead of casting it every time). A rule of thumb: (declare your variable) as general as you can and as specific as needed. – xerx593 Mar 23 '23 at 17:57

0 Answers0