这里很简单,我已经连接到 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);
}
DVDPropery
是一个设置属性,我使用表行值设置属性。
我有 2 行包含以下数据
1 疤面煞星
2 头像
每次我运行循环时,我的 ArrayList
都会覆盖
1 疤面煞星
与 2 头像两次
我希望每次都向我的 ArrayList
添加一个新行
并且它不会覆盖
最佳答案
在循环内实例化DVDProperty
。当前您正在重用同一实例,从而覆盖其属性:
while (res.next()) {
DVDProperty context = new DVDProperty();
...
}
关于java - 将 while 循环中的项目添加到 ArrayList java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580728/