
在java中,对象(包括arraylist)的变量实际上存储在对堆内存中实际对象的引用中。当我们将一个对象作为参数传递给方法或赋值给另一个变量时,我们传递的是对象的引用,而不是对象本身的副本。
这意味着,如果多个变量或对象引用相同的ArrayList实例,则通过任何引用(如添加或删除元素)对ArayList的操作都会影响所有引用ArayList的变量或对象。
这就是原始代码示例中的问题:
ArrayList<String> c = new ArrayList<String>();
// ... 添加选项 ...
q.add(new Question("Geography","Which ocean is the largest?", c, "Pacific", "..."));
// 此时,Question对象内部存储是对变量c指向的ArrayList实例的引用。
c.removeAll(c); // ArrayList实例中的所有元素都被清空了变量c所指向的。
// 因为Question对象持有相同ArrayList实例的引用,
// 所以它的choices列表也会被清空。
// ... 添加新的选项 ...
q.add(new Question("Geography", "How many countries are in the world?", c, "195", "..."));
// 此时,第一个Question对象的choices列表也成为第二个Question对象的choices。
c.removeAll(c) 操作清空了c目前指向的ArrayList对象的内容。因为之前创建的Question对象也持有这个同一个Arraylist对象的引用,因此当c被清空或修改时,所有引用其Question对象的choices列表都会同步更新,导致数据混乱。
解决方案:ArrayListt每次实例化新要解决这个问题,最直接和推荐的方法是确保每个Question对象都有自己独立的Arraylist实例作为choices列表。这意味着在为每个Question对象准备选项时,应该创建一个新的Araylist实例,而不是重用和清空之前的实例。
立即学习"Java免费学习笔记(深入);
将代码中的 c.removeAll(c); 替换为 c = new ArrayList<String>(); 可以实现这一点。每次。 c = new ArrayList<String>(); 执行时,会在堆内存中创建一个全新的ArrayList对象,并让变量c指向这个新对象。这样,之前创建的Question对象仍然持有对旧ArayList的引用,而新的Question对象则持有对新ArayList的引用,两者不相互影响。
修改后的代码示例以下是根据上述解决方案进行修正的 allInitialQuestions 方法:
import java.util.ArrayList;
import java.util.List; // 假设Question构造函数接受Listttttion<String>
// 假设Question类定义如下(简化示例)
class Question {
String genre;
String questionText;
List<String> choices; // 使用List接口更通用
String answer;
String funFact;
public Question(String genre, String questionText, List<String> choices, String answer, String funFact) {
this.genre = genre;
this.questionText = questionText;
// 注:为防止外部修改,防御性复制通常在这里进行
// 但在这种特定的场景下,我们已经确保新的例子被引入,因此,直接赋值也无妨
this.choices = choices;
this.answer = answer;
this.funFact = funFact;
}
// Getter方法(省略)
public List<String> getChoices() {
return choices;
}
@Override
public String toString() {
return "Question{" +
"genre='" + genre + '\'' +
", questionText='" + questionText + '\'' +
", choices=" + choices +
", answer='" + answer + '\'' +
", funFact='" + funFact + '\'' +
'}';
}
}
public class Database { // 假设这是包含allinitialQuestions方法的类别
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q) {
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>(); // 创建新的ArrayList实例
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>(); // 创建新的ArrayList实例
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>(); // 创建新的ArrayList实例
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>(); // 创建新的ArrayList实例
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>(); // 创建新的ArrayList实例
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;
}
}注意事项和最佳实践
- 理解引用和值传递: 这是Java编程的核心概念。基本数据类型(int, char, bolean等。)是按值传递的,而对象是按引用传递的。深刻理解这一点可以避免许多与数据共享相关的错误。
-
防御性复制(Defensive Copying): 在Question类的结构函数中,如果choices列表是从外部传输的,并且您希望Question对象内部的choices列表不受外部修改的影响,那么最好的实践是进行防御性复制。
public Question(String genre, String questionText, List<String> choices, String answer, String funFact) { // ... this.choices = new ArrayList<>(choices); // 创建一份传入列表的副本 // ... }这样,即使Question对象创建后修改了外部传入的choices列表,Question对象内部的数据也不会受到影响。
-
不可变集合(Immutable Collections): 如果Question对象创建后不应修改choices列表,则可以考虑使用不可变集合。
-
Java 9+ List.of(): List.of("Pacific", "Atlantic", ...) 不可变列表可以直接创建。
q.add(new Question("Geography", "Which ocean is the largest?", List.of("Pacific", "Atlantic", "Arctic", "Indian"), "Pacific", "...")); -
Collections.unmodifiableList(): 可变列表可以包装成不可变列表。
ArrayList<String> tempChoices = new ArrayList<>(); tempChoices.add("Pacific"); // ... q.add(new Question("Geography", "...", Collections.unmodifiableList(tempChoices), "...", "..."));不可变集合的使用可以提高代码的强度和安全性,因为它可以防止意外的数据修改从设计层面。
-
Java 9+ List.of(): List.of("Pacific", "Atlantic", ...) 不可变列表可以直接创建。
- 代码可读性: 清晰创建新对象的比例和清空旧对象可以更清晰地表达代码意图。虽然创建新对象的性能成本很小,但与代码的正确性、可维护性和可读性相比,这种成本在绝大多数应用场景中是微不足道的。
在处理Java中的集合对象时,请务必警惕引用传输引起的数据共享问题。当需要为不同的实体存储独立的数据集时,核心原则是为每个实体提供其独家的集合实例。通过每个新的实例,或防御复制、不可变集合等策略,可以有效地避免引用共享引起的数据意外修改,以确保程序的正确性和稳定性。
以上是ArrayList在Java中引用的陷阱和解决方案:避免数据意外修改的详细内容,请关注图灵教育的其他相关文章!