为什么有些人使用List基类来实例化一个新的ArrayList? [英] Why do some people use the List base class to instantiate a new ArrayList?

查看:44
本文介绍了为什么有些人使用List基类来实例化一个新的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆