Update objects stored in List by reference - Java Collection Framework

Java examples for Collection Framework:List

Introduction

Array lists contain references to objects, not the objects themselves, any changes you make to an object in an array list are automatically reflected in the list.

Demo Code

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Employee> emps = new ArrayList<Employee>();

    // add employees to array list
    emps.add(new Employee("A"));
    emps.add(new Employee("T"));
    emps.add(new Employee("K"));

    // print array list
    System.out.println(emps);/*  w ww. j  av  a2s.  c om*/

    // change one of the employee's names
    Employee e = emps.get(1);
    e.setName("new name");

    // print the array list again
    System.out.println(emps);

  }

}
class Employee{
  private String name;

  public Employee(String name) {
    this.name = name;
  }


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "Employee [name=" + name + "]";
  }

}

Related Tutorials