This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes what is the use of iterator() method in ArrayList..? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "what is the use of iterator() method in ArrayList..?" Watch "what is the use of iterator() method in ArrayList..?" New topic
Author

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

Damodara Reddy
Ranch Hand

Joined: Feb 09, 2007
Posts: 44
what is the significance of iterator() method in ArrayList class when we have get method to retrieve the elements?


Damu
Prafulla N. Patil
Ranch Hand

Joined: Mar 20, 2006
Posts: 106
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


Thanks, Prafulla Patil
SCJP, SCWCD
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
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.


Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
Damodara Reddy
Ranch Hand

Joined: Feb 09, 2007
Posts: 44
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

Joined: Feb 09, 2007
Posts: 44
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

Joined: Apr 14, 2004
Posts: 10336

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.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Damodara Reddy
Ranch Hand

Joined: Feb 09, 2007
Posts: 44
Thanks for your reply Paul Sturrock.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what is the use of iterator() method in ArrayList..?
 
Similar Threads
Blocking I/O using Iterator()
Traversing an ArrayList
Iterator of an ArrayList
ArrayList seems to be not working
using Iterator or without using Iterator