Java Reference
In-Depth Information
Each iteration will search transactions from the element given by the index stored in the variable
position . The initial value of -1 is incremented in the while loop condition, so on the first iteration it is 0.
On subsequent iterations where indexOf() finds an occurrence of aTransaction , the loop condition
increments 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 indexOf() will return
-1 and the loop will end by executing the break statement. If aTransaction happens to be found in the
last element in the Vector at index position size-1 , the value of position will be incremented to size by
the loop condition expression, so the expression will be false and the loop will end.
Applying Vectors
Let's implement a simple example to see how using a Vector works out in practice. We will write a
program to model a collection of people, where we can add the names of the persons that we want in
the crowd from the keyboard. We'll first define a class to represent a person:
public class Person {
// Constructor
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
public String toString() {
return firstName + " " + surname;
}
private String firstName; // First name of person
private String surname; // Second name of person
}
The only data members are the String members to store the first and second names for a person. By
overriding the default implementation of the toString() method, provided by the Object class, we
allow objects of the Person class to be used as arguments to the println() method for output, since
as you are well aware by now, toString() will be automatically invoked in this case.
Now we can define a class that will represent a crowd. We could just create a Vector object in main() but
this would mean any type of object could be stored. By defining our own class we can ensure that only
Person objects can be stored in the Vector and in this way make our program less prone to errors.
The class definition representing a crowd is:
import java.util.*;
class Crowd {
// Constructors
public Crowd() {
// Create default Vector object to hold people
people = new Vector();
}
public Crowd(int numPersons) {
Search WWH ::




Custom Search