最近在学习java,在这个过程中,我想着偷懒,没有按照视频来,发现了一个知识误区,记录一下
定义学生类代码如下
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类代码如下:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
//创建Collection对象
Collection<Student> c=new ArrayList<Student>() ;
Student s=new Student("林青霞",20);
c.add(s);
//对同一个对象重新赋值在加入集合
s.setAge(80);
s.setName("风清扬");
c.add(s);
////对同一个对象重新赋值在加入集合
s.setAge(50);
s.setName("张曼玉");
c.add(s);
Iterator<Student> it=c.iterator();
while(it.hasNext()){
Student s1=it.next();
System.out.println(s1.getName()+","+s1.getAge());
}
}
}
编译结果:

这个新的 Student 对象 s 并多次修改其属性后添加到集合中,但实际上集合中存储的是对同一个对象的多个引用。
在 Java 中,当您将一个对象添加到集合多次时,集合中存储的并不是多个独立的对象副本,而是对同一个对象的多个引用。所以,这个对象的后续修改会影响到集合中存储的所有该对象的引用,最终导致输出的结果看起来只有最后一次修改的状态。(可以理解为每次输出时会访问对象)
要解决这个问题,您需要在每次添加时创建新的 Student 对象,而不是重复使用同一个对象。
修改后:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
//创建Collection对象
Collection<Student> c=new ArrayList<Student>() ;
Student s=new Student("林青霞",20);
c.add(s);
Student s2=new Student("风清扬",20);
c.add(s2);
Student s3=new Student("赵一曼",20);
c.add(s3);
Iterator<Student> it=c.iterator();
while(it.hasNext()){
Student s1=it.next();
System.out.println(s1.getName()+","+s1.getAge());
}
}
}

2112

被折叠的 条评论
为什么被折叠?



