Thursday, May 19, 2011

Iterating over elements of a Vector API of java

You can use a for loop to get all the elements from a Vector, but another very common 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()) {

No comments:

Post a Comment