0

Why would you ever use List (interface) instead of ArrayList (class), as the latter seems to offer more possibilities and flexibility?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jonathan
  • 63
  • 6
  • Check this question on stack out: https://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n – Niels Van Steen Nov 06 '21 at 09:22
  • Actually, this Q&A shows that it is **less** flexible in some cases: https://stackoverflow.com/questions/1480663 – Stephen C Nov 06 '21 at 09:26
  • You want to use the most narrow type to do stuff with that type as it documents your usage better. A coder might wonder, "What method particular to an `ArrayList` is he using?" For example, if your code only uses `.size()`, you should use `Collection` instead of `List` or `ArrayList`. However, you want to return from a method with the most specific type you can always guarantee as it gives the user of that API more freedom to apply needed methods on that data. You should use `List` whenever all you need is defined on the `List` API. Consider using `Collection` or even `Iterable` if possible. – user904963 Nov 06 '21 at 10:33
  • 1
    Additionally, if an interface and a concrete type implement the same methods, you should prefer to use the type that is most appropriate based on a need to know basis in the class using that type. If your class truly relies on a `List` being implemented by `ArrayList`, you should use the latter. If it doesn't, you should use the former. This is a form of self-documenting code. The right type is the least specific as it restricts what can be done with it / how much to know about it, leading to an easier ability to understand what is happening. – user904963 Nov 06 '21 at 10:39

0 Answers0