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
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.
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
posted
0
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..?
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.