Isn’t it easier to work with foo when it is represented by the ArrayList class rather than the List interface?

I see this syntax a lot and do not understand the reasons underlying it. I thought that you usually want to work with classes, not with interfaces, in order to simplify the execution of all the operations that you might want to perform.

Why is this:

List<Foo> foo = new ArrayList<Foo>(something.getFoo());

instead of this:

ArrayList<Foo> foo = new ArrayList<Foo>(something.getFoo());

when will you later want to perform operations on foo? Isn’t it easier if foo is represented by the ArrayList class and not the List interface?

+3
source share
3 answers

Sometimes yes. If you really need a method declared in ArrayList<T>, but not in List<T>, then be sure to skip to it.

- - , ArrayList<T>, , List<T>. : " . ArrayList<T>, , ... , , ".

, - , , , . , ... , - .

, Iterable<T>, , : , . , - ..

, , , : , , .

+11

, , - -.

, , , , .

, LinkedList A ArrayList B.

.

+1

The whole point of polymorphism is to NOT bind your implementation to another data type implementation. In this case, you do not want to marry your class with an ArrayList. Rather, you want to marry your class to an abstract list type.

0
source

Source: https://habr.com/ru/post/1761021/


All Articles