英文:
How to run ArrayList.add() immediately?
问题
ArrayList<Student> list = new ArrayList<>();
/* Student只包含(ID、name、semester以及ArrayList<String> course)*/
int ID;
String name, semester;
ArrayList<String> course = new ArrayList<>();
然后我向列表中添加了一些学生
ID = 123;
name = "Hoang Van Lam";
semester = "Spring2020";
course.add("JAVA");
course.add("C#");
course.add("PYTHON");
list.add(new Student(ID, name, semester, course));
course.clear();
之后,我想要添加更多的学生,我尝试使用course.clear(); 来重新使用course。
然后我意识到course.clear() 在list.add()之前就已经执行了。那么我该如何解决这个问题呢?谢谢大家!
英文:
ArrayList<Student> list = new ArrayList<>();
/*Student just have (ID,name,semester and ArrayList<String> course */
int ID;
String name, semester;
ArrayList<String> course = new ArrayList<>();
Then I add some student to list
ID= 123;
name = "Hoang Van Lam";
semester = "Spring2020";
course.add("JAVA");
course.add("C#");
course.add("PYTHON");
list.add(new Student(ID,name,semester,course));
course.clear();
After that, I want to add more students, I try to use course.clear();
to reuse cousre
.
Then I realized that course.clear
had run before list.add ()
had taken it.So How can i improve this problem? Thanks all
答案1
得分: 2
当你将一个对象传递给构造函数时,实际上是传递了它的 "引用"。因此,当你调用 course.clear()
时,你只是清空了它,此时该对象在任何地方都为空!如果你想要一个新的列表,你可以创建一个并再次使用 course
来引用它:
ID = 123;
name = "Hoang Van Lam";
semester = "Spring2020";
course.add("JAVA");
course.add("C#");
course.add("PYTHON");
list.add(new Student(ID, name, semester, course));
course = new ArrayList<>();
英文:
When you pass an Object to the constructore you pass its "reference" so when you call course.clear()
you simply clear it and now the object is empty anywhere! If you want to have a new list you can create one and use course
to refer to it again :
ID= 123;
name = "Hoang Van Lam";
semester = "Spring2020";
course.add("JAVA");
course.add("C#");
course.add("PYTHON");
list.add(new Student(ID,name,semester,course));
course= new ArrayList<>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论