为什么有些人使用List基类来实例化一个新的ArrayList? [英] Why do some people use the List base class to instantiate a new ArrayList?
问题描述
我不断遇到人们实例化新ArrayList并将其分配给List接口的代码,如下所示:
I keep coming across code where people instantiate a new ArrayList and assign it to the List interface, like this:
List<String> names = new ArrayList<String>();
这种方法背后的原因是什么?
What is the reasoning behind this approach?
推荐答案
将代码与接口的特定实现分离。
To decouple your code from a specific implementation of the interface.
这也有助于您移动到另一个实现将来列出
界面。
This also helps you to move to another implementation of the List
interface in the future.
例如 -
你有 List< String> names = new ArrayList< String>();
稍后您决定使用 List
界面的其他一些实现,比如 LinkedList
因此您只需将其更改为 List< String> names = new LinkedList< String>();
并且没有任何中断。
You have List<String> names = new ArrayList<String>();
later on you decide that you should have used some other implementation of the List
interface, say LinkedList
so you would just change it to List<String> names = new LinkedList<String>();
and nothing breaks.
这篇关于为什么有些人使用List基类来实例化一个新的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!