修改 getter 的结果会影响对象本身吗? [英] Does modifying the result of a getter affect the object itself?
问题描述
我有一个关于在 Java 中使用 getter 方法的问题.假设我有这门课:
I have a question about using getter methods in java. Suppose I had this class:
class Test {
private ArrayList<String> array = new ArrayList<String>();
public ArrayList getArray() {
return this.array;
}
public void initArray() {
array.add("Test 1");
array.add("Test 2");
}
}
class Start {
public static void main(String args[]) {
initArray();
getArray().remove(0);
}
}
我的问题是:
实际的arraylist 对象是否会被修改(测试1"从中删除)?我想我已经在某些地方看到过这种情况,但我认为 getter 只是提供了该对象的副本.不是对它的引用.如果它确实以这种方式工作(作为参考),那么这是否也有效(Test 类的 arraylist 对象是否也会由此改变)?:
Would the actual arraylist object be modified ("Test 1" removed from it)? I think I have seen this in places, but I thought that getters were simply providing a copy of that object. Not a reference to it. If it did work that way (as a reference), then would this work as well (Would the arraylist object of the class Test be altered by this as well)?:
class Start {
public static void main(String args[]) {
initArray();
ArrayList aVar = getArray();
aVar.remove(0);
}
}
推荐答案
Java 返回对 Array 的引用,因此它不会是副本,而是会修改 List.通常,除非它是原始类型(int
、float
等),否则您将获得对对象的引用.
Java returns references to the Array, so it won't be a copy and it will modify the List. In general, unless its a primitive type (int
,float
,etc) you will be getting a reference to the object.
如果你想返回一个重复的数组,你必须自己显式复制数组.
You have to explicitly copy the array yourself if you want a duplicate to be returned.
这篇关于修改 getter 的结果会影响对象本身吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!