• Post Reply Bookmark Topic Watch Topic
  • New Topic

add element to list while iterating it.  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we add an element to a list while iterating the same list?
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only if you use a List and a ListIterator; the latter has an add method. Alternatively, you can choose to not use an Iterator and iterate the hard way:
Note that:
a) don't add an element in each and every iteration or the list size will increase along with i and the difference will always remain the same, therefore the loop will never end.
b) don't use this trick with LinkedList as it's inefficient to call get().
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesn't the RandomAccess interface tell us when that trick works?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will work regardless. RandomAccess will tell us if it will be efficient or not.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, Rob, agree. RandomAccess is there to show whether it is fast.
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that in Rob's example, iterating the List using the for-each loop / enhanced for-loop, will result in a java.util.ConcurrentModificationException, because it uses an Iterator behind the scenes.
 
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, RandomAccess just tells us whether the get(i) is fast. The indexed add(i, obj) tends to be an O(n) operation, regardless (at least for both ArrayList and LinkedList, given a random distribution of i). So I would really advocate using the ListIterator as Rob previously alluded:
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's still an O(n) operation for ArrayList though, as it shifts all later elements up by one. That's something you can't avoid for ArrayList. For LinkedList it will definitely perform (a lot) better.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!