我在Vaadin和Java新我处理以下问题:ArrayList中插入多个元素
在下面的代码,我想在ArrayList的“newlist”添加多个元素。如您所见,名为“ps”的元素有5个子元素。
问题是在ArrayList中添加的当前(in-the-loop)元素正在替换每个索引中的所有前面的元素,因此最终它只返回最后一个“ps”元素,次循环发生。
我如何可以存储在不同的索引中的每个 “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++
}
put'PS_SECTION ps = new PS_SECTION();'在for循环中。另外...你不应该完全用大写给类名。 “PsSection”将符合java命名约定。 –
为了解释_911DidBush_说的是什么,你需要在你的循环中创建一个'PS_SECTION'的新实例,在这里你正在更新同一个实例'ps'并且一次又一次地添加它 – AxelH
谢谢!这有帮助! – natso