I have two Classes:
Class1 which contains an ArrayList of type Class2
When I try to add a new object as follow:
Class2 object = new Class2();
Class1Object.getArrayList().add(object);
Then it appears that the object has been added when I iterate over getArrayList()
However I have another ArrayList of type class1 and when I iterate over this there object added does not appear?
I thought that since objects are by reference it should be added to the ArrayList of type class1. Can any one explain this please?
public class Subject implements Serializable {
private static final long serialVersionUID = 1L;
private String subjectName;
private int hours;
private int mins;
private ArrayList<Task> tasks;
private SimpleDateFormat date;
public Subject(String subjectName){
this.subjectName = subjectName;
hours = 0;
mins = 0;
tasks = new ArrayList<Task>();
date = null;
}
public ArrayList<Task> getTasks() {
return tasks;
}
}
public class Task implements Serializable {
private static final long serialVersionUID = 2L;
private String description;
private boolean isCompleted;
public Task(String description){
this.description = description;
isCompleted = false;
}
}
So then I have:
ArrayList<Subject> subjectsList = new ArrayList<Subject>();
And then I want to add a new task to a given subject so I do:
Task task = new Task(description);
ArrayList<Task> taskList = subject.getTasks();
taskList.add(task);
And when I iterate over subject.getTasks();
its there but when I iterate over subjectsList the new task is not there anymore.
Here is the first loop which shows the new task:
for (Task task : subject.getTasks()){
System.out.println( task.toString() );
}
And the code for iterating over all objects from subjectsList
for (Subject s : subjectsList){
for (Task t : s.getTasks()){
System.out.println( t.toString() );
}
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
subject = (Subject) bundle.get("selected_subject");
subjectsList = (ArrayList<Subject>) bundle.get("subjects_list");
}