Java Reference
In-Depth Information
7.8 Indexed Files
The previous section showed how to retrieve a part record given the record number. But this is not the most natural
way to retrieve records. More likely than not, we would want to retrieve records based on some key , in this case, the
part number. It is more natural to ask, “How many of BLJ375 do we have?” rather than “How many of record 2 do we
have?” The problem then is how to retrieve a record given the part number.
One approach is to use an index . Just as a book index lets us quickly locate information in a book, a file index
enables us to quickly find records in a file. The index is created as the file is loaded. Later, it must be updated as
records are added to, or deleted from, the file. In our example, an index entry will consist of a part number and a
record number.
We will use the following class for creating an index:
class Index {
String partNum;
int recNum;
public Index(String p, int r) {
partNum = p;
recNum = r;
}
} //end class Index
We will use MaxRecords to denote the maximum number of records we will cater for. We declare an array, index ,
as follows:
Index[] index = new Index[MaxRecords + 1];
We will use index[0].recNum to hold numRecords , the number of records stored in the file. The index entries will
be stored in index[1] to index[numRecords] .
The index will be kept in order by part number. We want to create an index for the following records:
PKL070 Park-Lens 8 6.50
BLJ375 Ball-Joint 12 11.95
FLT015 Oil-Filter 23 7.95
DKP080 Disc-Pads 16 9.99
GSF555 Gas-Filter 9 4.50
We assume that the records are stored in the file in the given order. When the first record is read and stored, the
index will contain this:
PKL070 1
This means that the record for PKL070 is record number 1 in the parts file. After the second record ( BLJ375 ) is
read and stored, the index will be this:
BLJ375 2
PKL070 1
 
Search WWH ::




Custom Search