class set ArrayList () method

ArrayList class set () method is used to update the contents of the specified location, if the new content out, call the set () method; otherwise, not need to call the set () method, the following examples

User.java

public class User {

    private int id;
    private String name;

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
  //省略get、set方法 }

main.java

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

public class main {

    public static void main(String[] args) {
        User user1 = new User(1, "a1");
        User user2 = new User(2, "a2");
        List list = new ArrayList();
        list.add(user1);
        list.add(user2);
        for (int i=0; i<list.size(); i++){
            System.out.println(list.get(i));
        }
        System.out.println("*******************" ); user1.setId (

         11 ); 
        user1.setName ( "A11");    // here only modify the attributes of the object user1 , the need to call set ArrayList () method works by 
        for ( int I = 0; I <list.size (); I ++ ) { 
            System.out.println (List.get (I)); 
        } 
        the System.out. the println ( "*******************" ); user1

         = new new the User (111, "A111" ); 
        list.set ( 0, user1);      // user1 objects the new object is new, so here must call set ArrayList () method to take effect 
        for ( int I = 0; I <list.size (); I ++ ) {  
            System.out.println (List.get (I) );
        } 
    } 
}

operation result

Guess you like

Origin www.cnblogs.com/yanguobin/p/12040085.html