且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 中的 ArrayList 或 List 声明

更新时间:2023-11-29 17:32:16

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.