【问题标题】:all the elements of vector replace by the last object - java向量的所有元素都替换为最后一个对象-java
【发布时间】:2013-11-15 13:06:42
【问题描述】:

我在这里尝试将对象添加到向量并从向量中取回元素。 在 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 公共类学生实现 java.io.Serializable {

    private int coursework1;



    public int getCoursework1() {
        return coursework1;
    }
    public void setCoursework1(int coursework1) {
        this.coursework1 = coursework1;
    }

}

【问题讨论】:

  • 您每次都在添加对同一个 Student 对象的引用。将student = new Student() 移动到循环内 - 并使其成为局部变量,理想情况下......这个问题是许多其他问题的欺骗,但我现在没有精力找到它们......

标签: java oop vector


【解决方案1】:

从当前位置删除 student = new Student(); 并将其放在你的 for 循环中。

for(int i=0; i<MAX_STUDENT; i++){
    student = new Student();  // Added here     
    System.out.print("Coursework 01 Marks : ");

}

【讨论】:

  • 非常感谢。非常感谢您的支持。
  • 很遗憾,我没有足够的声望投票给你的答案。
【解决方案2】:

您只创建了 1 个Student 对象,并且不断将其添加到向量中。 将对象添加到向量并不意味着您正在实例化一个新对象。如果您查看您的代码,您只调用了一次 new Student(),这意味着您有一个对象,您一直从向量的每个字段引用该对象。

这一行

student.setCoursework1(input.nextInt());

不断为同一对象的coursework1 属性赋值。

【讨论】:

  • 注意!!谢谢你的时间:)
【解决方案3】:

只创建了一个在循环之外的 Student 对象。因此,为了使其工作,您必须在每次循环运行时创建一个对象。

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    相关资源
    最近更新 更多