在这里,我试图将对象添加到矢量并从矢量中获取元素。在 for 循环向量中给出了所有 3 个对象的详细信息。但我想让对象在循环之外。但它只提供第三个对象的详细信息。
static Vector<Student> vector = null;
static Student student= null;
public static void AskStudentDetails(){
Scanner input = new Scanner(System.in);
student = new Student();
vector = new Vector<Student>();
for(int i=0; i<MAX_STUDENT; i++){
System.out.print("Coursework 01 Marks : ");
student.setCoursework1(input.nextInt());
vector.addElement(student); //add object to the vector
Student mm = vector.elementAt(0);
System.out.println(mm.getCoursework1());
}
input.close();
student = vector.elementAt(1);//assign to the object student
System.out.println(student.getCoursework1()); // always print only the value of third object
}
学生.class public class Student 实现 java.io.Serializable {
private int coursework1;
public int getCoursework1() {
return coursework1;
}
public void setCoursework1(int coursework1) {
this.coursework1 = coursework1;
}
}
从当前位置删除student = new Student();
并将其放置在 for 循环中。
for(int i=0; i<MAX_STUDENT; i++){
student = new Student(); // Added here
System.out.print("Coursework 01 Marks : ");
}
您只创建了 1 个Student
对象,并且不断将其添加到向量中。将对象添加到向量并不意味着要实例化新对象。如果您查看代码,则只会调用new Student()
一次,这意味着您有一个对象,您可以从向量的每个字段不断引用该对象。
此行
student.setCoursework1(input.nextInt());
不断为同一对象的 coursework1
属性赋值。
只创建一个在循环外的学生对象。 因此,为了使它工作,您必须在每次循环运行时创建一个对象。
for(int i=0; i<you_length; i++){
student = new Student(); //this is what you have to add. every time a new object is created.
System.out.print("etc");
}