2016-12-01 66 views
0

我在Vaadin和Java新我处理以下问题:ArrayList中插入多个元素

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

问题是在ArrayList中添加的当前(in-the-loop)元素正在替换每个索引中的所有前面的元素,因此最终它只返回最后一个“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++      
       } 
+5

put'PS_SECTION ps = new PS_SECTION();'在for循环中。另外...你不应该完全用大写给类名。 “PsSection”将符合java命名约定。 –

+1

为了解释_911DidBush_说的是什么,你需要在你的循环中创建一个'PS_SECTION'的新实例,在这里你正在更新同一个实例'ps'并且一次又一次地添加它 – AxelH

+0

谢谢!这有帮助! – natso

回答

2
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++      
       } 

尝试把你的实例化loop内设置的值之前。像上面的代码一样。

您在此循环中实例化PS_SECTION的原因是创建一个新的instanceobjectPS_SECTION。如果你在loop以外实例化它,你只需要创建一个对象用于你的loop,这就是为什么你在ArrayList中添加的所有对象都是一样的objects

+1

试着解释为什么下一次...因为这是在评论中解释! – AxelH

+0

好的,先生@AxelH,我会编辑和解释。谢谢你的方式。 – msagala25

+0

@natso我编辑它,并解释为什么你需要在for循环中实例化它。学分给先生AxelH。 – msagala25