Java Reference
In-Depth Information
while(theData.hasNext())
System.out.println((String)theData.next());
This loop iterates through all the elements referenced by
theData
one at a time, and outputs each
String
object to the display. When we've retrieved the last element from the
Iterator
, the method
hasNext()
will return
false
and the loop will end.
You can also obtain a
ListIterator
reference from a vector by calling the
listIterator()
method:
ListIterator listIter = names.listIterator();
Now you can go backwards or forwards though the objects using the
ListIterator
methods that
we saw earlier.
It is also possible to obtain a
ListIterator
object that encapsulates just a part of the vector, using a
version of the
listIterator()
method that accepts an argument specifying the index position of the
first vector element in the iterator:
ListIterator listIter = names.listIterator(2);
This statement will result in a list iterator that encapsulates the elements from
names
from the element
at index position 2 to the end. The argument must not be negative and must be less than the size of
names
, otherwise an
IndexOutOfBoundsException
will be thrown. Take care not to mix the
interface name with a capital L with the method name with a small l.
To cap that, you can retrieve an internal subset of the objects in a vector as a collection of type
List
using the
subList()
method:
List list = names.subList(2, 5); //Extract elements 2 to 4 as a sublist
The first argument is the index position of the first element from the vector to be included in the list,
and the second index is the element at the upper limit -
not
included in the list. Thus this statement
extracts elements 2 to 4 inclusive. Both arguments to
subList()
must be positive, the first argument
must be less than the size of the vector, and the second argument must not be greater than the size,
otherwise an
IndexOutOfBoundsException
will be thrown.
There are lots of ways of using the
subList()
method in conjunction with other methods, for example:
ListIterator listIter = transactions.subList(5, 15).listIterator(2);
Here we obtain a list iterator for elements 2 to the end of the list returned by the
subList()
call, which
will be elements 7 to 14 inclusive from the
transactions
vector.