gpt4 book ai didi

java - ArrayList插入多个元素

转载 作者:行者123 更新时间:2023-12-02 03:11:58 26 4
gpt4 key购买 nike

我是 Vaadin 和 Java 的新手,我正在处理以下问题:

在下面的代码中,我想在ArrayList“newlist”中添加多个元素。正如您所看到的,名为“ps”的元素有 5 个子元素。

问题是 ArrayList 中添加的当前(循环中)元素正在替换每个索引中的所有先前元素,因此最终它仅返回最后一个“ps”元素,多次当循环发生时。

enter image description here

如何将每个“ps”元素存储在不同的索引中?

代码:

Collection<?> itemIds =  table.getItemIds();
Item item = null;
PS_SECTION ps = new PS_SECTION();
List<PS_SECTION> newlist = new ArrayList<PS_SECTION>();
int i = 0;

for(Object itemId : itemIds){

item = table.getItem(itemId);// row
Long s1 = (Long) item.getItemProperty("ID").getValue();
String s2 = item.getItemProperty("ΕΝΟΤΗΤΑ").getValue().toString();
Long s3 = (Long) item.getItemProperty("ΔΙΑΤΑΞΗ").getValue();
Long s4 = 0L;
Long s5 = 0L;

ps.setPS_SECTION(s1);
ps.setNAME(s2);
ps.setVORDER(s3);
ps.setISACTIVE(s4);
ps.setISGLOBAL(s5);

newlist.add(ps);
i++
}

最佳答案

Collection<?> itemIds =  table.getItemIds();
Item item = null;
PS_SECTION ps = null; // Declare first ps to null, because you will instantiate it later
List<PS_SECTION> newlist = new ArrayList<PS_SECTION>();
int i = 0;

for(Object itemId : itemIds){

item = table.getItem(itemId);// row
Long s1 = (Long) item.getItemProperty("ID").getValue();
String s2 = item.getItemProperty("ΕΝΟΤΗΤΑ").getValue().toString();
Long s3 = (Long) item.getItemProperty("ΔΙΑΤΑΞΗ").getValue();
Long s4 = 0L;
Long s5 = 0L;

ps = new PS_SECTION() // put it here your instantiation
ps.setPS_SECTION(s1);
ps.setNAME(s2);
ps.setVORDER(s3);
ps.setISACTIVE(s4);
ps.setISGLOBAL(s5);

newlist.add(ps);
i++
}

在设置值之前,尝试将实例化放入循环中。就像上面的代码一样。

在循环中实例化 PS_SECTION 的原因是为该对象创建一个新的实例 PS_SECTION 。如果您在 loop 之外实例化它,则只需创建 1 个要在 loop 中使用的对象,这就是您在 ArrayList< 中添加的所有内容的原因 都是相同的对象

关于java - ArrayList插入多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907604/

26 4 0