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);
}
}
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.
Do it in a single line
prevoiusList.subList(0,6).clear()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With