Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java create subList and remove values from previous List

Tags:

java

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

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);
     }
}    
like image 430
Erik Avatar asked May 19 '13 11:05

Erik


2 Answers

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.

like image 183
BobTheBuilder Avatar answered Oct 27 '22 09:10

BobTheBuilder


Do it in a single line

prevoiusList.subList(0,6).clear()
like image 45
naveejr Avatar answered Oct 27 '22 09:10

naveejr