Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the use of iterator() method in ArrayList..?

 
Damodara Reddy
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the significance of iterator() method in ArrayList class when we have get method to retrieve the elements?
 
Prafulla N. Patil
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
with the help of get method you can get only one element in the list
but with iterator you can iterate through all the elements of ArrayList, even without knowing index
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also you can safely change the contents of the ArrayList of which you are iterating. If you use a for loop and you're changing the contents of the ArrayList this could lead to unexpected results.
 
Damodara Reddy
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that we can do with the help of get also, like
for(int i=0;i<=al.length;i++)
// write get here get(i);
 
Damodara Reddy
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Remko Strating.
I hope , iterator() is also going to help us when we take ArrayList into a Collection, as we dont have get method in Collection.
But what is the need of taking an arrayList into a collection..?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would use a Collection to allow you room to change which implementation you wanted to use. Suppost originally all you needed was something to hold a list of objects, well an ArrayList will do fine. But then you realise that the values of the objects in this collection must be unique so you change it to a Set. If you had used the get() method of List to iterate through your collection you would need to change this code. If you had used an Iterator then nothing needs changed.
 
Damodara Reddy
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply Paul Sturrock.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic