File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes removeAll on sub list ad the same collection produce different result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "removeAll on sub list ad the same collection produce different result" Watch "removeAll on sub list ad the same collection produce different result" New topic
Author

removeAll on sub list ad the same collection produce different result

Vasiliy Zaicev
Greenhorn

Joined: Sep 20, 2012
Posts: 1
Dear All.
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.

Output:
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?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18992
    
    8

The API documentation for subList says:

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.
Nikhil Sagar
Ranch Hand

Joined: Apr 21, 2012
Posts: 216

We call it Backed Collection.


OCPJP 6 86%
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: removeAll on sub list ad the same collection produce different result