修改吸气剂的结果是否会影响对象本身? [英] 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")?我认为我已经在某些地方看到了这一点,但是我认为吸气剂只是提供了该物体的一个副本.没有引用它.如果它确实以这种方式起作用(作为参考),那么它也会起作用(是否也会因此改变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.
这篇关于修改吸气剂的结果是否会影响对象本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!