Replace object in List by reference - Java Collection Framework

Java examples for Collection Framework:ArrayList

Introduction

You can pass the actual object you want removed.

Demo Code

import java.util.ArrayList;

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

    // create employee objects
    Employee emp1 = new Employee("A");
    Employee emp2 = new Employee("T");
    Employee emp3 = new Employee("K");

    // add employee objects to array list
    emps.add(emp1);// w w w.  j  a v  a2  s.  com
    emps.add(emp2);
    emps.add(emp3);

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

    // remove one of the employees
    emps.remove(emp2);

    // 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