Java Reference
In-Depth Information
Retrieving Objects
As you saw in the simple example earlier, if you have the index for an element in a vector, you can obtain
the element at that position by using the
get()
method. For the
names
vector you could write the following:
String name = names.get(4);
This statement retrieves the fifth element in the
names
vector. The return type for the
get()
method is
determined by the type argument you used to create the
Vector<>
object.
The
get()
method throws an
ArrayIndexOutOfBoundsException
if the argument is an illegal index
value. The index must be non-negative and less than the size of the vector.
You can retrieve the first element in a vector using the
firstElement()
method. For example:
String name = names.firstElement();
You can retrieve the last element in a vector by using the
lastElement()
method in a similar manner.
Neither method is implemented in the
ArrayList<>
class. However, both a vector and an array list have the
flavor of a list about them, and if you want to process the objects like a list, you can obtain an iterator.
Accessing Elements in a Vector through a List Iterator
You've already seen how you can obtain all the elements in a vector using an
Iterator<>
object, so I won't
repeat it. You can also obtain a
ListIterator
reference by calling the
listIterator()
method:
ListIterator<String> listIter = names.listIterator();
Now you can go backward or forward though the objects in
names
using the
ListIterator
methods that
you saw earlier.
It is also possible to obtain a
ListIterator<>
object that encapsulates just a part of a vector, using a
listIterator()
overload that accepts an argument specifying the index position in the vector of the first
element in the iterator:
ListIterator<String> listIter = names.listIterator(2);
This statement results in a list iterator that encapsulates the elements from
names
from index position 2
to the end. If the argument is negative or greater than the size of
names,
an
IndexOutOfBoundsException
is thrown. Take care not to confuse the interface name
ListIterator
, with a capital
L,
with the method of
the same name, with a small
l
.
Additionally, you can retrieve an internal subset of the objects as a collection of type
List<>
using the
subList()
method:
List<String> 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 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
IndexOutOfBoundsEx-