java - 对象数组添加仅添加最后一条记录

标签 java object arraylist

我正在尝试将一个对象添加到数组列表中。

该对象定义为:

ExercisesGroup group = new ExercisesGroup();

数组列表定义为:

ArrayList<ExercisesGroup> groups = new ArrayList<ExercisesGroup>();

然后我在循环中填充对象(rs 是来自数据库的结果集):

while (rs.next()){
    group.setExerciseGroupId(rs.getInt("idbodyarea"));
    group.setExerciseGroupDescription(rs.getString("bodyareadescription"));
    groups.add(group);
}

当我返回数组列表“组”时,会添加正确数量的结果,但数据都是相同的,即为每个槽添加最后一条记录。

<exerciseGroupsReturn>
        <exerciseGroupDescription>Description2</exerciseGroupDescription>
        <exerciseGroupId>2</exerciseGroupId>
 </exerciseGroupsReturn>
 <exerciseGroupsReturn>
        <exerciseGroupDescription>Description2</exerciseGroupDescription>
        <exerciseGroupId>2</exerciseGroupId>
 </exerciseGroupsReturn>

知道我做错了什么吗?

最佳答案

您需要在每次迭代时创建该对象的新实例:

while (rs.next()){
   group = new ExercisesGroup();
   //...
}

另外,如果你改变groups的声明会更好。变量来自 ArrayList<ExercisesGroup>List<ExercisesGroup> 。引用What does it mean to "program to an interface"?

关于java - 对象数组添加仅添加最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221224/

相关文章:

java - 在启用 Spring Data Mongodb 审核的情况下运行测试

javascript - 如果两个 JavaScript 对象数组共享元素,当一个数组不再被引用时,所有非共享内存是否都会被垃圾回收?

c++ - 创建重复对象的 vector ?

java - 计算数组列表中关键字的出现次数

java - 将 ArrayList 中的 <E> 留给类来决定

java - 如何将JTable添加到JTabbedPane中?

java - 删除Java中重载的方法

java - .getClass().getName() 方法为何适用于 int 类型?

javascript - Library.add 不是函数错误

java - 我的程序存在问题,涉及数组列表、缓冲读取器、方法以及对 Java 工作原理的总体遗忘