0

I was a bit confused, when we use

List<String> lst = new LinkedList<>();     

when we use

LinkedList<String> lklst = new LinkedList<>();

At the beginning, I thought they are the same, but today, I realized they are not the same. For example, if I call lst.getFirst() It will tell me there is a error. However, if i do lklst.getFirst(), it works fine. My question is when do we use lklst then? why they are different? Also, does it apply same rule for Map. THanks!

Ryan Chen
  • 9
  • 2

1 Answers1

1

On the left hand side you're declaring the type of the variable, lst. Since lst's type is List you can only access methods of a List, even if the object lst points to is really a LinkedList. There's an inherent tradeoff between declaring a variable of a concrete type like LinkedList (access to more methods / behavior) vs. a more abstract interface (safer, better compartmentalized code).

This is a big topic, and there isn't one simple answer for when to do one vs. the other (though there's lots of advice out there about it!) - you'll need to figure out which is appropriate for your use case.

Effective Java - Item 52: Refer to objects by their interfaces is a pretty canonical citation for this issue, and as the title implies suggest preferring List rather than LinkedList.

dimo414
  • 47,227
  • 18
  • 148
  • 244