【发布时间】:2019-03-14 17:02:56
【问题描述】:
我无法确定是否可以在不使用类设置器方法的情况下更改所有引用。 我也仅限于 java.util.* 方法。
想象一下这段代码:
public static void main(String[] args) {
List<Apple> first = new ArrayList<>();
List<Apple> second = new ArrayList<>();
Apple someApple = new Apple(5);
first.add(someApple);
second.add(someApple);
Apple changeIt = first.get(0);
// Is it possible to change / rewrite object changeIt (no class setters available)
}
public static class Apple {
int size;
public Apple (int size){
this.size = size;
}
public int getSize() {
return size;
}
}
目标是更改List<Apple> second 中的相同对象。我不能直接访问List<Apple> second 也不能直接访问类设置器。
编辑> 也许这段代码更好地解释了这种情况:
List<Obj> doSomething = cantTouch.getUseThis();
public class Obj {
var SomeVariables;
public Obj(){}
}
public class cantTouch {
private static List<Obj> tryToModify = new ArrayList<>();
public static List<Obj> useThis = new ArrayList<>();
public static void createObj() {
Obj someObj = new Obj();
tryToModify.add(someObj);
useThis.add(someObj);
}
public static List<Obj> getUseThis(){
return useThis;
}
}
【问题讨论】:
-
列表不包含对象。它们包含对对象的引用。您的示例显示了包含对同一对象的引用的两个列表。如果您通过任一引用在一个对象上调用了 mutator 方法,则该对象将被更改。如果您更改了一个列表中的引用,它不会自动更改另一个列表中的引用。