Search This Blog

Friday, April 21, 2006

Using ListIterator for Vector : Java

Vertor is any dynamic array and A simple way to go over all elements in a Vector is to use a ListIterator. The advantage of an iterator is that it it can be used with other data structures, so that if you later change to using a linked list for example, you won't have to change your code. Here is an example of using an iterator to print all elements (Strings) in a vector. The two most useful methods are hasNext(), which returns true if there are more elements, and next(), which returns the next element.

ListIterator iter = v.listIterator();
while (iter.hasNext()) {

1 comment:

Anonymous said...

Thats fine. but want to know its advantages interms of performance like speed. If the list is not dynamic, it is preferred to use the normal way like below and iterate thru:
for(int i=0 ; i< objects.size() ; i++)