Java 中的 ArrayList 或 List 声明 [英] ArrayList or List declaration in Java

查看:42
本文介绍了Java 中的 ArrayList 或 List 声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个声明有什么区别?

What is the difference between these two declarations?

声明 1:

ArrayList<String> arrayList = new ArrayList<String>();

声明 2:

List<String> arrayList = new ArrayList<String>();

推荐答案

List<String> arrayList = new ArrayList<String>();

在返回给客户端时想要隐藏实现细节的通用性,稍后您可以将实现从 ArrayList 透明地更改为 LinkedList.

Is generic where you want to hide implementation details while returning it to client, at later point of time you may change implementation from ArrayList to LinkedList transparently.

这种机制在您设计库等的情况下很有用,这些库可能会在某个时间点更改其实现细节,而客户端的更改最少.

This mechanism is useful in cases where you design libraries etc., which may change their implementation details at some point of time with minimal changes on client side.

ArrayList<String> arrayList = new ArrayList<String>();

这要求您始终需要返回 ArrayList.在某些时候,如果您想将实现细节更改为 LinkedList,客户端也应该更改为使用 LinkedList 而不是 ArrayList>.

This mandates you always need to return ArrayList. At some point of time if you would like to change implementation details to LinkedList, there should be changes on client side also to use LinkedList instead of ArrayList.

这篇关于Java 中的 ArrayList 或 List 声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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