Can someone explain me why it is happening.
If I construct ArraysList of integers containing 4, 1, 3, 6, 4, 4, 1;
then get sublist from index 1 to index 4- I will get new collection 1,3,6
Then If I will call removeAll(subList) original collection will hold 4, 4, 1.
1: [4, 1, 3, 6, 4, 4, 1]
sub: [1, 3, 6]
2: [4, 4, 1]
Note If I will not use sublist removeAll will remove all 1,3,6 so I will get 4,4,4.
Why removeAll behave this way when used on subList?
The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)
And that is what you did. You modified the backing list ("integers") in such a way that its size was changed. So that means that what's in your "sub" list may not be what you think.
I notice that your test program doesn't display the "sub" list after you call removeAll. Try that and see what happens.