返回ArrayList或List? [英] Return ArrayList or List?

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

问题描述

我正在创建一个供人们使用的库,但为什么我的方法会返回列表而不是 ArrayList

I'm creating a library to be used by people but why should my method return a List instead of an ArrayList?

因为如果用户知道真实类型是 ArrayList ,他将在循环中使用accessor []而不是迭代器,但如果他不知道他将使用迭代器。

Because if the user knows the real type is an ArrayList he will use the accessor [] in a loop instead of iterator but if he doesn't know he will use an iterator.

LinkedList 的同样问题,如果返回类型是List,他将无法使用正确的访问者。

Same question for LinkedList, if the return type is a List he won't be able to use the correct accessor.

我是对的吗?

推荐答案

返回列表将使您的库的用户可以使用任何实现 List 界面的内容,而使用 ArrayList 会强制他们使用 ArrayList

Returning List will make it possible for users of your library to use anything that implements a List interface, while using an ArrayList will force them to use an ArrayList.

如果将来您作为图书馆创建者决定更改您的内部实施,那么这些更改将通过您的通用界面从最终用户隐藏图书馆。

If in the future, you as a library creator decide to change your internal implementation, that changes will be hidden from the end user by the generic interface to your library.

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

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