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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4580728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:02:52  来源:igfitidea点击:

Adding items from a while loop to an ArrayList java

javalistcollectionspropertiesarraylist

提问by Calibre2010

Simple one here, I have connected to a sqldb and from my database I am retrieving rows from a table.

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

For each row i wish to save the data to an ArrayList. Each row being an item in the ArrayList.

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

This is what I have so far.

这就是我迄今为止所拥有的。

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

DVDProperyis a set property where i set the properties with the table row values.

DVDPropery是一个设置属性,我在其中使用表行值设置属性。

I have 2 rows with the following data

我有 2 行包含以下数据

1 Scarface
2 Avatar

1 疤面煞星
2 阿凡达

Everytime I Run through the loop my ArrayListoverrides 1 Scarface with 2 Avatar twice

每次我运行循环时,我都会ArrayList用 2 个头像两次覆盖 1 Scarface

I wish to add a new row to my ArrayListeach time and it not override

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

回答by Bozho

Instantiate DVDPropertyinside the loop. Currently you are reusing the same instance, and thus overriding its properties:

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

while (res.next()) {
   DVDProperty context = new DVDProperty();
   ...
}

回答by Karol Lewandowski

You have to create new object of type DVDProperty for every record. At this time you change the same object (context) in every iteration. Try:

您必须为每条记录创建类型为 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);
}

回答by karan shah

Please create new instance of the DVDProperty object in loop everytime it runs the loop.
Please refer to code snippet below.

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