Skip to content
Advertisement

How to run ArrayList.add() immediately?

 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

Advertisement

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<>();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement