Erik Erik -4 years ago 191
Java Question

Java create subList and remove values from previous List

I want to create a subList in Java and remove values that are in subList from the previous List. My program correctly creates subList, but than it doesn't remove the correct values from previousList.

My Code:

for(int i=0; i<4; i++){
List<Object> sub=new ArrayList<Object>(prevoiusList.subList(0,6));

for (int j=0; j<6; j++){
previousList.remove(j);
}
}

Answer Source

At first j=0 and you remove the first element. When doing so you shift all other elements, so the second element becomes first and so on.

On next iteration j=1, so you remove the second element, which was originally the third...

In order to fix this issue, use only 0 index, or an iterator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download