是更好地使用列表或集合? [英] Is it better to use List or Collection?

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

问题描述

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

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.

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

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