如何立即运行ArrayList.add()?

huangapple go评论68阅读模式
英文:

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&lt;Student&gt; list = new ArrayList&lt;&gt;(); 
   /*Student just have (ID,name,semester and ArrayList&lt;String&gt; course */

 int ID;
 String name, semester;
 ArrayList&lt;String&gt; course = new ArrayList&lt;&gt;();

Then I add some student to list

        ID= 123;
        name = &quot;Hoang Van Lam&quot;;
        semester = &quot;Spring2020&quot;;
        course.add(&quot;JAVA&quot;);
        course.add(&quot;C#&quot;);
        course.add(&quot;PYTHON&quot;);
        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 = &quot;Hoang Van Lam&quot;;
semester = &quot;Spring2020&quot;;
course.add(&quot;JAVA&quot;);
course.add(&quot;C#&quot;);
course.add(&quot;PYTHON&quot;);
list.add(new Student(ID,name,semester,course));
course= new ArrayList&lt;&gt;();

huangapple
  • 本文由 发表于 2020年9月16日 13:15:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63913570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定