natso natso - 2 days ago 4
Java Question

ArrayList inserting multiple elements

I am new in Vaadin and Java and I am dealing the problem below:

In the following code, I want to add multiple elements in the ArrayList "newlist". As you can see, the elements named "ps" have 5 sub-elements.

The problem is that the current(in-the-loop) element added in the ArrayList is replacing all the previous ones in each index and as a result in the end it returns only the last "ps" element, as many times as the loop is occured.

enter image description here

How can I store each "ps" element in the different indexes?

And the code:

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

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

Try to put your instantiation within the loop before you set the values. like the code above.

Comments