Java List change custom object element

Description

Java List change custom object element

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

class Language {//www.  j  av a 2  s. c om
  private String name;
  private String id;

  public Language(String name, String id) {
    this.name = name;
    this.id = id;
  }

  public String getName() {
    return name;
  }

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

  public String getId() {
    return id;
  }

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

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

  public static String toString(Collection<Language> langs) {
    String s = "";
    for (Language l : langs) {
      s += l + "\n";
    }
    return s;
  }

}

public class Main {

  public static void main(String[] args) {
    List<Language> langList = new ArrayList<>();
    langList.add(new Language("CSS", "1"));
    langList.add(new Language("HTML", "2"));
    
    System.out.println(Language.toString(langList));
    
    langList.get(1).setId("new Id");
    
    System.out.println(Language.toString(langList));
    
  }

}



PreviousNext

Related