Java Reference
In-Depth Information
The remove() method searches the Vector for the first Employee that is equal
to s. Because two Employee objects are equal if they have the same number, the
employee who is number 4 is removed. The index of the removed employee is
different each time the program is executed because of the random order in
which the Vector is filled.
The following statement removes the object at index 7 from the employees
Vector:
employees.remove(7);
The size of the vector is now 8, and the for loop uses the elementAt() method
to traverse through the Vector and pay each Employee object. Figure 9.9 shows
the output.
The Vector class is useful in situations in which you need a resizeable
array. However, in terms of performance, Vectors can be quite inefficient if
elements are continually being added and removed. Each time an element
is added in the middle, all the elements beyond the inserted element
need to be moved up one (index increases by one). Similarly, deleting an
element causes all elements beyond the deleted element to be moved
back one (their index decreases by one). When using a Vector, try to limit
the number of arbitrary insertions and deletions.
The Hashtable Class
A hash table is a data structure that maps keys to values. A hash table can be
viewed as a collection of buckets, with each bucket able to hold any number of
entries. Adding an object to a hash table involves deciding which bucket to
place the object in, a process referred to as hashing.
Every object in the hash table generates a hash code as determined by its
hashcode() method. Every object has a hashcode() method that it inherits from
java.lang.Object. A class that is to be used with hash tables should override the
hashcode() method and return a unique value for different objects. The general
rule is that if two objects are not equal as determined by their equals() method,
the two objects should return different hash codes.
For example, the Employee class in the following listing uses the employee's
number as its hash code. Notice that the equals() method in Employee defines
two Employee objects as equal if they have the same number, which means
that different Employee objects have a different hash code.
Search WWH ::




Custom Search