I have this code which adds some objects to an ArrayList. Then, from the List, in Step 1, I modify the contents of these objects -- and the backing objects themselves also change, which works. Then, in Step 2, from the List I set my objects to NULL. The list changes - I can see its elements are NULL, but the backing objects do not change. Why is that?
My expectation: a, b, c are set to NULL.
public class Test {
static class Student
{
String name;
int age;
public Student(String name, int age) { this.name = name; this.age = age; };
public String getName() { return name; }
public int getAge() { return age; }
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
}
public static void main(String[] args)
{
Student a = new Student("John", 20);
Student b = new Student("Mary", 21);
Student c = new Student("Bill", 22);
ArrayList<Student> students = new ArrayList<Student>();
students.add(a);
students.add(b);
students.add(c);
// STEP 1: Changing contents from list: THIS WORKS - Referenced objs change (a, b, c)
for (int i = 0; i < students.size(); i++)
students.get(i).setName("NEW NAME");
// STEP 2: Setting to null from list: DOES NOT WORK - Referenced objs do NOT change (a, b, c)
for (int i = 0; i < students.size(); i++)
students.set(i, null);
}