使用 List 还是 Collection 更好? [英] Is it better to use List or Collection?

查看:41
本文介绍了使用 List 还是 Collection 更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在列表中存储一些数据的对象.实现可能会在以后更改,我不想将内部实现公开给最终用户.但是,用户必须能够修改和访问此数据集合.目前我有这样的事情:

I have an object that stores some data in a list. The implementation could change later, and I don't want to expose the internal implementation to the end user. However, the user must have the ability to modify and access this collection of data. Currently I have something like this:

public List<SomeDataType> getData() {
   return this.data;
}

public void setData(List<SomeDataType> data) {
   this.data = data;
}

这是否意味着我允许内部实现细节泄露?我应该这样做吗?

Does this mean that I have allowed the internal implementation details to leak out? Should I be doing this instead?

public Collection<SomeDataType> getData() {
   return this.data;
}

public void setData(Collection<SomeDataType> data) {
   this.data = new ArrayList<SomeDataType>(data);
}

推荐答案

这取决于,您是否希望您的用户能够对数据进行索引?如果是,请使用列表.两者都是接口,因此您不会泄露实现细节,实际上,您只需要确定所需的最低功能即可.

It just depends, do you want your users to be able to index into the data? If yes, use List. Both are interfaces, so you're not leaking implementation details, really, you just need to decide the minimum functionality needed.

这篇关于使用 List 还是 Collection 更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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