返回对象引用的最佳实践 [英] Best Practice for Returning Object References
问题描述
请考虑以下代码段:
class MyClass{
private List myList;
//...
public List getList(){
return myList;
}
}
由于Java按值传递对象引用,我的理解是任何调用 getList()
的对象都将获得对 myList
的引用,允许它修改 myList
尽管它是 private
。这是正确的吗?
As Java passes object references by value, my understanding is that any object calling getList()
will obtain a reference to myList
, allowing it to modify myList
despite it being private
. Is that correct?
如果它是正确的,我应该使用
And, if it is correct, should I be using
return new LinkedList(myList);
创建副本并传回对副本的引用,而不是原始副本,以便防止未经授权访问 myList
引用的列表?
to create a copy and pass back a reference to the copy, rather than the original, in order to prevent unauthorised access to the list referenced bymyList
?
推荐答案
我做那。更好的是,有时我会使用Collections API返回一个不可修改的副本。
I do that. Better yet, sometimes I return an unmodifiable copy using the Collections API.
如果不这样做,那么你的引用不是私有的。任何有参考的人都可以改变您的私人状态。对于任何可变引用(例如,Date)也是如此。
If you don't, your reference is not private. Anyone that has a reference can alter your private state. Same holds true for any mutable reference (e.g., Date).
这篇关于返回对象引用的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!