Java – is it easier to use foo when it is represented by the class ArrayList rather than the interface list?

I see a lot of grammar and don't understand the reasons behind it I think you usually want to use classes instead of interfaces to more easily perform all the operations you may want to perform

Why do things turn out like this?

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

Not this:

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

When you want to perform operations on foo in the future? Isn't it easier if foo is represented by the class ArrayList instead of the interface list?

Solution

Occasionally, yes If you really need a method declared in ArrayList < T > but not in list < T >, be sure, go

However, the reverse is more flexible – if you don't need any methods declared in ArrayList < T >, your code can be represented by declaring variables of type list < T > Replace That is to say, "I just need a list. I happened to choose ArrayList < T >, but just because its behavior suits me... Not because I need any additional features it exposes."

For example, it's useful to know if anyone wants to know if they can replace different implementations in the future It also limits how much the reader must consider... The more common the type of variable, the less it is used - so the less it needs to be considered

For example, if I see a variable of type iteratable < T > I know it will probably be used to do very few things in the future: basically, it will be used to iterate, and that's all I don't need to worry about whether future code will try to add values to the collection, or access it through indexes, etc

This is relatively unimportant for local variables, but especially for instance variables, especially parameters: the less specific the parameters are, the more flexible the caller is about which parameters they will pass

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>