代码示例
import java.util.ArrayList;
import java.util.List;
public class ListAddObject {
static class Student {
private int Id;
public void setId(int Id) {
this.Id = Id;
}
@Override
public String toString() {
return "id = " + Id;
}
}
public static void main(String[] args) {
List<Student> list1 = new ArrayList<>();
Student stu1 = new Student();
for (int i = 0; i < 3; i++) {
stu1.setId(i);
list1.add(stu1);
}
System.out.println("list1: " + list1);
List<Student> list2 = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Student stu2 = new Student();
stu2.setId(i);
list2.add(stu2);
}
System.out.println("list2: " + list2);
List<Student> list3 = new ArrayList<>();
Student stu3 = null;
for (int i = 0; i < 3; i++) {
stu3 = new Student();
stu3.setId(i);
list3.add(stu3);
}
System.out.println("list3: " + list3);
}
}
运行结果: