将while循环中的项添加到ArrayList java

Cal*_*010 2 java collections properties list arraylist

这里很简单,我已连接到sqldb,从我的数据库中我正在从表中检索行.

对于每一行,我希望将数据保存到ArrayList.每行都是一个项目ArrayList.

这就是我到目前为止所拥有的.

List<DVDProperty> DVDList = new ArrayList<DVDProperty>();

DVDProperty context = new DVDProperty();

while (res.next()) {
    int i = res.getInt("idnew_table");
    String s = res.getString("dvdName");

    context.setDVDId(i);
    context.setDVDName(s);

    DVDList.add(context);
}
Run Code Online (Sandbox Code Playgroud)

DVDPropery 是一个set属性,我使用表行值设置属性.

我有2行,包含以下数据

1疤面煞星
2头像

每当我跑完循环时,我ArrayList会用2个阿凡达两次覆盖1个疤面煞星

我希望ArrayList每次都添加一个新行,而不是覆盖它

Boz*_*zho 12

DVDProperty在循环内实例化.目前,您正在重用相同的实例,从而覆盖其属性:

while (res.next()) {
   DVDProperty context = new DVDProperty();
   ...
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*ski 6

您必须为每条记录创建DVDProperty类型的新对象.此时,您在每次迭代中更改相同的对象(上下文).尝试:

List<DVDProperty> DVDList = new ArrayList<DVDProperty>();
while (res.next()) {
    int i = res.getInt("idnew_table");
    String s = res.getString("dvdName");
    DVDProperty context = new DVDProperty();
    context.setDVDId(i);
    context.setDVDName(s);
    DVDList.add(context);
}
Run Code Online (Sandbox Code Playgroud)