Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

removeAll on sub list ad the same collection produce different result

 
Vasiliy Zaicev
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 216
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We call it Backed Collection.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic