
在java编程中,我们经常需要将一个集合(如araylist)作为参数传递给类的构造函数或方法,以初始化对象内部的属性。一个常见的陷阱是,当这个集合是可变类型时(mutable)如果同一集合实例的引用是传递的,那么后续对该集合的修改将影响持有该引用的所有对象。
考虑以下场景:我们有一个Question类,其构造函数接受ArrayListtion类<String>作为选项列表。我们希望为每个Question对象设置独立的选项。但是,如果我们在循环中重复使用相同的ArrayList变量,并通过清空它(removeAll)并通过重新添加元素来准备新的选项,就会出现问题。
以下是原始代码示例,展示了这种意想不到的行为:
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q) {
ArrayList<String> c = new ArrayList<String>(); // 声明ArrayList用于存储选项
// 第一个问题
c.add("Pacific");
c.add("Atlantic");
c.add("Arctic");
c.add("Indian");
// 将当前c的引用传递给Question构造函数
q.add(new Question("Geography","Which ocean is the largest?", c, "Pacific", "The Pacific Ocean stretches to an astonishing 63.8 million square miles!"));
// 试着清空c,准备第二个问题的选项
c.removeAll(c); // 清空c中的所有元素
// 第二个问题
c.add("192");
c.add("195");
c.add("193");
c.add("197");
// 将当前c的引用传递给Question构造函数
q.add(new Question("Geography", "How many countries are in the world?", c, "195", "Africa has the most countries of any continent with 54."));
// 此时,Question对象的第一个选项列表也将成为 "192", "195", "193", "197"
// ... 后续问题也存在同样的问题
return q;
}
在上述代码中,当我们创建第一个Question对象时,其内部选项列表实际上存储在变量c引用的Arraylist对象中。当c.removeAll(c)当被调用时,它清空了c引用的Arraylist对象中的所有元素。由于第一个Question对象持有相同的Araylist引用,其选项也将被清空。然后,当我们将第二个问题选项添加到c中时,这些新选项也会出现在第一个Question对象的选项列表中,因为它们共享了相同的底部Araylist实例。
2. 对Java引用的对象有深刻的理解Java中的所有对象(包括Arraylist)都是通过引用来操作的。当您声明变量并使用new关键字创建对象时,变量实际上存储对象的内存地址(即引用)。
立即学习“Java免费学习笔记(深入);
ArrayList<String> list1 = new ArrayList<>(); // list1 引用了一个新的ArrayList对象
ArrayList<String> list2 = list1; // list2 还引用了同一个ArrayList对象
list2.add("Hello"); // list2修改后,list1也可以看到变化
在问题代码中,ArrayList<String> c = new ArrayList<String>(); 创建ArrayList对象,并让变量c引用它。当q.add(new Question(..., c, ...))当被调用时,Question的构造函数接收到c引用的Arraylist对象的内存地址。如果Question直接将此引用赋值给其成员变量,那么Question对象和外部c变量将共享相同的Araylist实例。
因此,当执行c时.removeAll(c)当时,共享的ArrayList实例实际上被清空了。然后在c中添加新元素,也在这个共享实例中添加,影响了所有引用它的Question对象。
3. 解决方案:为每个实例创建独立的集合解决这个问题的核心是确保每个Question对象都有自己独立的选项列表副本,而不是共享相同的例子。最直接有效的方法是每次为新的Question准备选项时,都会实例化一个新的Arraylist对象。
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q) {
// 每次为新问题准备选项时,都会创建新的ArrayList实例
ArrayList<String> c; // 声明变量,但暂时不初始化
// 第一个问题
c = new ArrayList<String>(); // 为第一个问题创建新的ArrayList实例
c.add("Pacific");
c.add("Atlantic");
c.add("Arctic");
c.add("Indian");
q.add(new Question("Geography","Which ocean is the largest?", c, "Pacific", "The Pacific Ocean stretches to an astonishing 63.8 million square miles!"));
// 第二个问题
c = new ArrayList<String>(); // 为第二个问题创建新的ArrayList实例
c.add("192");
c.add("195");
c.add("193");
c.add("197");
q.add(new Question("Geography", "How many countries are in the world?", c, "195", "Africa has the most countries of any continent with 54."));
// 后续问题
c = new ArrayList<String>(); // 为第三个问题创建新的ArrayList实例
c.add("Mississippi");
c.add("Nile");
c.add("Congo");
c.add("Amazon");
q.add(new Question("Geography", "What is the name of the longest river in the world?", c, "Nile","Explorer John Hanning Speke discovered the source of the Nile on August 3rd, 1858."));
c = new ArrayList<String>();
c.add("United States");
c.add("China");
c.add("Japan");
c.add("India");
q.add(new Question("Geography","Which country has the largest population?" ,c, "China", "Shanghai is the most populated city in China with a population of 24,870,895."));
c = new ArrayList<String>();
c.add("Mars");
c.add("Mercury");
c.add("Venus");
c.add("Jupiter");
q.add(new Question("Geography","Which planet is closest to Earth?",c,"Venus","Even though Venus is the closest, the planet it still ~38 million miles from Earth!"));
c = new ArrayList<String>();
c.add("Sega");
c.add("Nintendo");
c.add("Sony");
c.add("Atari");
q.add(new Question("Video Games", "Which company created the famous plumber Mario?", c, "Nintendo", "Nintendo created Mario in 1981 for the arcade game Donkey Kong."));
c = new ArrayList<String>();
c.add("Sonic");
c.add("Tales");
c.add("Knuckles");
c.add("Amy");
q.add(new Question("Video Games", "What is the name of the famous video character who is a blue hedgehog?",c,"Sonic", "In some official concept art, Sonic was originally meant to be a rabbit."));
c = new ArrayList<String>();
c.add("Wii Sports");
c.add("Grand Theft Auto V");
c.add("Tetris");
c.add("Minecraft");
q.add(new Question("Video Games","As of 2022, which of the following is the best selling video game of all time?",c,"Minecraft","As of 2022, Minecraft has sold over 238 million units."));
return q;
}
通过将c.removeAll(c);替换为c = new ArrayList<String>();,我们保证,每次创建Question对象并传递选项列表时,都会传递一个全新独立的Arraylist实例。这样,每个Question对象都有自己独家的选项列表,其中一个列表的修改不会影响其他Question对象。
4. 最佳实践和注意事项理解引用与值: 始终记住,Java中的对象变量存储的是引用,而不是对象本身。引用的操作可能会影响指向同一对象的所有引用。
-
防御性复制(Defensive Copying): 在类结构函数或setter方法中,如果接收可变集作为参数,且不希望外部修改影响内部状态,则应进行防御性复制。
public class Question { private final List<String> choices; public Question(String genre, String questionText, List<String> choices, String answer, String funFact) { // 防御复制,确保内部List和外部参数List相互独立 this.choices = new ArrayList<>(choices); // ... 其他属性 } // ... 其他方法 }即使外部引入的List被修改,Question对象内部的choices也不会受到影响。
不可变集合: 如有可能,考虑使用不可变集合。例如,Collections.unmodifiableList(List<T> list)您可以返回不可修改的列表视图。虽然这并不能阻止原始列表被修改,但它可以防止通过返回视图进行修改。更彻底的是,Guava和其他图书馆提供的真正不可变的集合可以使用。
局部变量及作用域: 该方法创建的局部变量的生命周期仅限于该方法。但是,如果局部变量的引用被传输并存储在外部对象中,引用对象将继续存在,直到没有引用指向它。
在处理Java中的可变集合时,请务必注意对象引用传输的特性。当需要为多个对象分配独立的集合数据时,避免重用相同的集合实例,并通过清空“重置”数据。正确的方法是为每个需要独立集合的对象实例提供一个新的集合。此外,在设计类别中,采用防御复制等策略可以有效地提高程序的强度和数据隔离,避免共享引用造成的事故数据串行更改问题。
以上是Java中ArrayList引用传递问题和解决方案的详细内容。请关注图灵教育的其他相关文章!