Java Reference
In-Depth Information
// Create Vector object to hold people with given capacity
people = new Vector(numPersons);
}
// Add a person to the crowd
public boolean add(Person someone) {
return people.add(someone); // Use the Vector method to add
}
// Get the person at a given index
Person get(int index) {
return (Person)people.get(index);
}
// Get number of persons in crowd
public int size() {
return people.size();
}
// Get people store capacity
public int capacity() {
return people.capacity();
}
// Get an iterator for the crowd
public Iterator iterator() {
return people.iterator();
}
// Person store - only accessible through methods of this class
private Vector people;
}
We've defined two constructors for the class for illustration purposes. One creates a Vector with a
default capacity, and the other creates a Vector with the capacity given by the argument. Both
constructors just call the appropriate Vector constructor. You could easily add the ability to provide
the capacity increment with a third constructor, if you want.
By keeping the Vector member of the class private , we ensure the only way an object can be added
to the Vector is by using the add() method in the class. Since this method only accepts an argument
of type Person , we can be sure that it's impossible to store elements of any other type. Of course, if
you wanted to allow other specific types to be stored, an object of type Child for example, you could
arrange to derive the class Child from Person , so the add() method would allow an argument of
type Child , since Person would be its superclass.
The remaining methods here are just to show how simple it is to implement the equivalent of the
Vector methods for our class. In each case they use the Vector method to produce the required
result. Now we are ready to put together a working example.
Try It Out - Creating the Crowd
We can now add a class containing a main() method to test these classes. We'll call it TryVector :
Search WWH ::




Custom Search