• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iteratoring List and adding object in the list  RSS feed

 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am using Iterator to iterate a List. but in the iterator i need to add element based on some condition is it possible ? as i can see that there is no add method in the Iterator. May be i can use list.add in the iterator, but that might cause some problem.

Is there any Collecitons Utility method which i can use in this scenerio ?

Thanks

Jigar Naik
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you adding to the same List you are iterating? That is not what you are supposed to do; an Iterator is intended for getting things out of the List. You would suffer a Concurrent Modification Exception if you did that.

Maybe, try a for loop instead.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An Iterator doesn't have an add() method - but a ListIterator does:

ConcurrentModificationException will not be an issue as long as you use the iterator itself to perform any modifications.

Maybe, try a for loop instead.

I would use a for loop in any event, but that's neither here nor there. Do you mean use a for loop to increment an index, and use list.get(i) to get elements? That can work, though the performace gets crappy if you're dealing with a large LinkedList. And add(i) is crappy for most any list, if i is in the middle. Whereas ListIterator tends to work well for any kind of List.
 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mike, but how does it work ? will create another list in memory for adding a new element ?
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you try it out? You'll learn much more from it.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!