Java Reference
In-Depth Information
index
if((position = names.indexOf(aName, position)) < 0) { // Find next
break;
}
++count;
}
This counts the number of occurrences of
a Name
in the
names
vector. The
while
loop continues as long
as the
indexOf()
method returns a valid index value and the index isn't incremented beyond the end of the
On each loop iteration, the
indexOf()
method searches
names
from the element given by the index stored
in
position
. The initial value of
-1
is incremented in the
while
loop condition, so on the first iteration it is
0. On subsequent iterations, as long as
indexOf()
finds an occurrence of
aName
, the loop condition incre-
ments
position
to the next element, ready for the next search. When no further references to the object can
be found from the position specified by the second argument, the method returns −1 and the loop ends by
executing the
break
statement. If
aName
is found in the last element in the vector at index position
size-1
,
the value of
position
is incremented to
size
by the loop condition expression, so the expression is
false
and the loop ends.
When you just want to know whether or not a particular element is stored, and don't really need to know
where it is, you can use the
contains()
method that returns
true
if the object you pass as the argument
is in the container and returns
false
otherwise. The
Vector<>
and
ArrayList<>
containers also have the
containsAll()
method. You pass a collection to this method as an argument of type
Collection
and the
method returns
true
if all the objects in the argument collection are also in the vector or array list.
Applying Vectors
Let's implement a simple example to see a
Vector<>
container working in practice. You write a program to
model a collection of people, where you can add the names of the persons that you want in the crowd from
the keyboard. You first define a class to represent a person:
public class Person {
// Constructor
public Person(String firstName, String surname) {
this.firstName = firstName;