0

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

4
  • Check this question on stack out: stackoverflow.com/questions/9852831/… Commented Nov 6, 2021 at 9:22
  • Actually, this Q&A shows that it is less flexible in some cases: stackoverflow.com/questions/1480663 Commented Nov 6, 2021 at 9: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. Commented Nov 6, 2021 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. Commented Nov 6, 2021 at 10:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.