• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

removeAll on sub list ad the same collection produce different result

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Marshal
Posts: 27371
88
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 216
Tomcat Server Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We call it Backed Collection.

 
Would anybody like some fudge? I made it an hour ago. And it goes well with a tiny ad ...
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic