ArrayList类的set()方法
ArrayList类的set()方法用于更新指定位置的内容,若内容是new出来的,则需要调用该set()方法;否则,不需要调用该set()方法,示例如下
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"); //此处只是修改了user1对象的属性,不需要调用ArrayList的set()方法就可以生效 for (int i=0; i<list.size(); i++){ System.out.println(list.get(i)); } System.out.println("*******************"); user1 = new User(111, "a111"); list.set(0, user1); //user1对象为新new的对象,所以此处必须调用ArrayList的set()方法才会生效 for (int i=0; i<list.size(); i++){ System.out.println(list.get(i)); } } }