
在java中,对象(包括arraylist)的传递方式是“按值传递引用”。这意味着当你将一个arraylist对象作为参数传递给一个方法或构造函数时,实际上传递的是该arraylist对象在内存中的地址(引用),而不是arraylist的副本。如果多个对象持有同一个arraylist的引用,那么通过任何一个引用对该arraylist进行的修改,都会反映在所有持有该引用的对象上。
考虑以下场景:你有一个Question类,其构造函数接受一个ArrayList<String>作为选择项。你希望为不同的问题设置不同的选择项,但发现当为新问题设置选择项并清空旧ArrayList时,之前已创建的问题的选择项也随之改变。
让我们通过一个示例代码来具体分析这个问题:
public class Question {
String genre;
String questionText;
ArrayList<String> choices;
String answer;
String funFact;
public Question(String genre, String questionText, ArrayList<String> choices, String answer, String funFact) {
this.genre = genre;
this.questionText = questionText;
this.choices = choices; // 这里是关键:直接引用了传入的ArrayList
this.answer = answer;
this.funFact = funFact;
}
// 为了演示,添加一个获取choices的方法
public ArrayList<String> getChoices() {
return choices;
}
@Override
public String toString() {
return "Genre: " + genre + ", Question: " + questionText + ", Choices: " + choices;
}
}
public class Database {
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q) {
ArrayList<String> c = new ArrayList<String>();
// 第一个问题
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!"));
// 问题所在:清空并重用同一个ArrayList 'c'
c.removeAll(c); // 等同于 c.clear();
// 第二个问题
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."));
// ... 后续问题也以相同方式处理 ...
return q;
}
public static void main(String[] args) {
ArrayList<Question> questions = new ArrayList<>();
allInitialQuestions(questions);
// 打印第一个问题,观察其choices是否被修改
if (!questions.isEmpty()) {
System.out.println("第一个问题: " + questions.get(0));
}
}
}在上述代码中,当第一个Question对象被创建时,它内部的choices字段引用了外部的ArrayList c。随后,c.removeAll(c)操作清空了ArrayList c。由于第一个Question对象仍然持有对这个被清空的ArrayList c的引用,因此它的选择项也被清空了。当c被重新填充并用于第二个Question对象时,第一个Question对象所引用的ArrayList也随之更新,显示为第二个问题的选择项。这就是数据意外串改的根本原因。
解决这个问题的关键在于确保每个Question对象都拥有自己独立的ArrayList实例,而不是共享同一个可变对象。最直接且推荐的方法是,在为每个Question对象准备选择项时,都创建一个全新的ArrayList实例。
立即学习“Java免费学习笔记(深入)”;
修改后的allInitialQuestions方法如下:
public class Database {
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q) {
// 第一个问题
ArrayList<String> c1 = new ArrayList<>(); // 创建新的ArrayList实例
c1.add("Pacific");
c1.add("Atlantic");
c1.add("Arctic");
c1.add("Indian");
q.add(new Question("Geography", "Which ocean is the largest?", c1, "Pacific", "The Pacific Ocean stretches to an astonishing 63.8 million square miles!"));
// 第二个问题
ArrayList<String> c2 = new ArrayList<>(); // 创建新的ArrayList实例
c2.add("192");
c2.add("195");
c2.add("193");
c2.add("197");
q.add(new Question("Geography", "How many countries are in the world?", c2, "195", "Africa has the most countries of any continent with 54."));
// 第三个问题
ArrayList<String> c3 = new ArrayList<>(); // 创建新的ArrayList实例
c3.add("Mississippi");
c3.add("Nile");
c3.add("Congo");
c3.add("Amazon");
q.add(new Question("Geography", "What is the name of the longest river in the world?", c3, "Nile","Explorer John Hanning Speke discovered the source of the Nile on August 3rd, 1858."));
// 第四个问题
ArrayList<String> c4 = new ArrayList<>(); // 创建新的ArrayList实例
c4.add("United States");
c4.add("China");
c4.add("Japan");
c4.add("India");
q.add(new Question("Geography","Which country has the largest population?" ,c4, "China", "Shanghai is the most populated city in China with a population of 24,870,895."));
// 第五个问题
ArrayList<String> c5 = new ArrayList<>(); // 创建新的ArrayList实例
c5.add("Mars");
c5.add("Mercury");
c5.add("Venus");
c5.add("Jupiter");
q.add(new Question("Geography","Which planet is closest to Earth?",c5,"Venus","Even though Venus is the closest, the planet it still ~38 million miles from Earth!"));
// 第六个问题
ArrayList<String> c6 = new ArrayList<>(); // 创建新的ArrayList实例
c6.add("Sega");
c6.add("Nintendo");
c6.add("Sony");
c6.add("Atari");
q.add(new Question("Video Games", "Which company created the famous plumber Mario?", c6, "Nintendo", "Nintendo created Mario in 1981 for the arcade game Donkey Kong."));
// 第七个问题
ArrayList<String> c7 = new ArrayList<>(); // 创建新的ArrayList实例
c7.add("Sonic");
c7.add("Tales");
c7.add("Knuckles");
c7.add("Amy");
q.add(new Question("Video Games", "What is the name of the famous video character who is a blue hedgehog?",c7,"Sonic", "In some official concept art, Sonic was originally meant to be a rabbit."));
// 第八个问题
ArrayList<String> c8 = new ArrayList<>(); // 创建新的ArrayList实例
c8.add("Wii Sports");
c8.add("Grand Theft Auto V");
c8.add("Tetris");
c8.add("Minecraft");
q.add(new Question("Video Games","As of 2022, which of the following is the best selling video game of all time?",c8,"Minecraft","As of 2022, Minecraft has sold over 238 million units."));
return q;
}
}在这个修改后的版本中,每次为Question对象创建选择项时,都通过new ArrayList<String>()创建了一个全新的ArrayList对象。这意味着每个Question实例的choices字段都引用了一个独立的ArrayList,它们之间互不影响。即使后续修改或清空了某个ArrayList,也不会影响到其他Question对象中存储的选择项。
除了在外部创建新实例,你也可以在Question类的构造函数内部进行处理,接收一个ArrayList作为参数,但在内部创建一个它的深拷贝。这样,即使外部的ArrayList被修改,Question对象内部的数据也不会受影响。
修改Question类的构造函数:
public class Question {
// ... 其他字段 ...
ArrayList<String> choices;
public Question(String genre, String questionText, ArrayList<String> choices, String answer, String funFact) {
this.genre = genre;
this.questionText = questionText;
// 在构造函数内部创建传入ArrayList的副本
this.choices = new ArrayList<>(choices); // 深拷贝
this.answer = answer;
this.funFact = funFact;
}
// ... 其他方法 ...
}然后,外部的allInitialQuestions方法可以恢复使用单个c变量并进行清空操作,因为Question构造函数会负责创建副本。
public class Database {
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q) {
ArrayList<String> c = new ArrayList<String>();
// 第一个问题
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.clear(); // 清空,不影响已创建的Question对象
// 第二个问题
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.clear(); // 清空,不影响已创建的Question对象
// ... 后续问题也以相同方式处理 ...
return q;
}
}这种方法的好处是外部代码可以更简洁地重用同一个ArrayList变量,而数据隔离的责任则转移到了Question类内部。
在Java中,处理ArrayList等可变对象的引用传递是常见的编程挑战。当将ArrayList作为参数传递给新创建的对象时,务必理解其引用行为。为了避免数据被意外修改,最佳实践是为每个对象提供一个独立的ArrayList实例,无论是通过在外部代码中每次new一个新列表,还是在目标对象的构造函数中进行深拷贝。掌握这些概念和技巧,将有助于编写更健壮、更可预测的Java应用程序。
以上就是Java教程:掌握ArrayList引用传递,防止数据意外修改的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号