0

Take the following two lines of code:

List<String> listOfStrings = new ArrayList<>();

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

I understand that it's good practice to program to Interfaces, however as a newbie, I'm trying to understand since we can only call List methods on both these instances, do they still "behave" like ArrayLists or LinkedLists (As in they perform like their respective classes when sorting/adding etc.)

hooknc
  • 4,854
  • 5
  • 31
  • 60
  • 5
    The type of the variable doesn't change the type of the object. They don't just "behave" like ArrayLists or LinkedLists, they still *are* ArrayLists or LinkedLists. – azurefrog Oct 30 '19 at 20:58
  • I think what confused me is that since you can only call the List methods I wasn't sure what they really "were", thanks for clarifying. – Antony Christodoulou Oct 30 '19 at 21:00
  • @AntonyChristodoulou You can think of an interface as being a sort of "contract". It's a way of saying, "I guarantee that no matter what type of object this actually is, it will still expose this list of methods for you to use." The actual logic behind those methods is of no concern to the interface, as long as it adheres to the contract. – Jordan Oct 30 '19 at 21:05
  • Thanks @Jordan. Now you reminded me of the purpose of Interfaces this syntax and its purpose now makes complete sense. – Antony Christodoulou Oct 30 '19 at 21:08
  • 1
    I'd suggest you take the time to read through [What does it mean to program to an interface?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface). There's a lot of good information in there. – azurefrog Oct 30 '19 at 21:10

2 Answers2

0

Yeah they do behave like ArrayList or LinkedList, you can use this to save more different Lists (or your own objects) and call different implementations of the superclass's methods while iterating over an Array.

0

Both LinkedList and ArrayList implemented List, Collection, Iterable... interfaces, but they have different implementation of methods (like add(), remove(), etc. Arraylist and LinkedList will have different behavior/performance due to different implementations, when calling these methods).

hydroPenguin
  • 66
  • 1
  • 4