What is the Vector.listIterator method in Java?
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.
Syntax
public ListIterator<E> listIterator()
Parameters
This method doesn’t take any arguments.
Return value
This method returns a ListIterator object with the elements of the Vector object.
Code
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() + " , ");}}}
Explanation
In the above code:
-
In lines 1 and 2: We imported the
VectorandListIteratorclasses. -
In line 5: We created a new
Vectorobject with the namevector. -
From lines 6-9: We added four elements(
1,2,3,4) to thevectorobject using theaddmethod. -
In line 10: We used the
listIteratormethod to get aListIteratorfor the elements of thevector. -
In line 13: We printed the elements of the
ListIteratorusing thewhileloop. We used thehasNextmethod of the iterator object to check if theListIteratorcontains more elements. We also used thenextmethod to get the element at the next cursor position.