Java Collection How to - Modify a member of an object from ArrayList








Question

We would like to know how to modify a member of an object from ArrayList.

Answer

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//from w ww  .ja  v a  2s.  co m
class Customer {
  private String name;
  private String email;

  public Customer(String name, String email) {
    this.name = name;
    this.email = email;
  }

  public String getName() {
    return name;
  }

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

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  @Override
  public String toString() {
    return name + " | " + email;
  }

  public static String toString(Collection<Customer> customers) {
    String s = "";
    for (Customer customer : customers) {
      s += customer + "\n";
    }
    return s;
  }

}

public class Main {

  public static void main(String[] args) {
    List<Customer> customers = new ArrayList<>();
    customers.add(new Customer("A", "a@gmail.com"));
    customers.add(new Customer("B", "b@gmail.com"));
    System.out.println("customers before email change - start");
    System.out.println(Customer.toString(customers));
    System.out.println("end");
    customers.get(1).setEmail("new.email@gmail.com");
    System.out.println("customers after email change - start");
    System.out.println(Customer.toString(customers));
    System.out.println("end");
  }

}

The code above generates the following result.