How to run ArrayList.add() immediately?

Tags: ,



 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

Answer

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<>();


Source: stackoverflow