The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index, and the size of aVectorcan be increased or decreased. Read more about theVectorhere.
The listIterator method of the Vector class will return a ListIterator over the elements in this vector. The returned ListIterator contains the elements in proper sequence.
The
ListIteratoris an iterator which we can use to traverse the list in both directions (forwards and backwards), modify the list, and get the index of the current position of the iterator. Also, it doesn’t have thecurrentElementlikeIterator. Read more about theListIteratorhere.
public ListIterator<E> listIterator()
This method doesn’t take any arguments.
This method returns a ListIterator object with the elements of the Vector object.
The below code demonstrates how to use the listIterator method.
import java.util.Vector;import java.util.ListIterator;class Capacity {public static void main( String args[] ) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(2);vector.add(3);vector.add(4);ListIterator<Integer> listIterator = vector.listIterator();System.out.println("The elements of the vector is ");while(listIterator.hasNext()) {System.out.print(listIterator.next() + " , ");}}}
In the above code:
In lines 1 and 2: We imported the Vector and ListIterator classes.
In line 5: We created a new Vector object with the name vector.
From lines 6-9: We added four elements(1,2,3,4) to the vector object using the add method.
In line 10: We used the listIterator method to get a ListIterator for the elements of the vector.
In line 13: We printed the elements of the ListIterator using the while loop. We used the hasNext method of the iterator object to check if the ListIterator contains more elements. We also used the next method to get the element at the next cursor position.