• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can using for-loop in place of iterator in case of ArrayList accomplish the same ?

 
Monica Shiralkar
Ranch Hand
Posts: 861
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iterators are used to iterate in java collections but if we specifically take the case of arrayList which has indexes.Does using for loop in place of iterator in case of arralList accomplish the same. We can iterate throught for loop also instead of arrray List.Isnt there any difference in case of arrayList?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cannot remember the last time I used an iterator.
 
Maneesh Godbole
Saloon Keeper
Posts: 11165
14
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For loop is useful when you wish to use the index of the element in your collection. Why would you want to use the index? That would depend on your requirement. One far fetched example is a collection of students sorted as per their exam marks. The topper is the 1st element in the collection. The duffer is the last.
Iterators are useful, when you wish to remove an element from your collection without running into the concurrent modification exception.
For everything else use the enhanced for loop, detailed out for you by Bear.
 
Volodymyr Lysenko
Ranch Hand
Posts: 512
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello !

If you mean foreach loop(by your word "for-loop") then foreach loop internally uses iterator() method.
You hear it right. Foreach loop uses internally iterator() method of collection you provide.
Recall that every class that implements Collection interface also implements Iterable interface.

However using iterator() you can remove elements while iterating by using foreach loop you can't.

If you mean for loop based on index then you can add,remove,replace elements.

To know internal life of ArrayList please cover my Internal life of ArrayList tutorial
 
Monica Shiralkar
Ranch Hand
Posts: 861
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic