Java Reference
In-Depth Information
int getDate (int index) throws RecordStoreException {
byte[] buf = days.getRecord (index);
return ((((int) buf [0]) & 0x0ff) << 24)
| ((((int) buf [1]) & 0x0ff) << 16)
| ((((int) buf [2]) & 0x0ff) << 8)
| ((((int) buf [3]) & 0x0ff));
}
The getIndex() method performs the binary search, returning the index of the day log of the given
date. If a day log for the given date does not exist, the negative index where the day log for the given
date should be inserted is returned:
public int getIndex (int date) throws RecordStoreException {
int i = 1;
int j = days.getNumRecords();
int k;
int dateK;
while (i <= j) {
k = (i + j) / 2;
dateK = getDate (k);
if (date == dateK) return k;
else if (date > dateK) i = k+1;
else j = k-1;
}
return -i;
}
The method for reading a DayLog of a given date is quite simple. First, the index for the given date is
calculated by calling getIndex() . Then, whether the index is negative or not, a new DayLog is
created or loaded from the record store:
public DayLog getDayLog (int date)
throws RecordStoreException, IOException {
int index = getIndex (date);
return (index == -1)
? new DayLog (date)
: new DayLog (days.getRecord (index));
}
Storing a DayLog is a bit more complicated. If an entry for the given date does not yet exist, all
following records need to be shifted in order to obtain space for the new record:
public void storeDayLog (DayLog dayLog)
throws RecordStoreException, IOException {
if (!dayLog.isDirty()) return;
int index = getIndex (dayLog.getDate());
byte [] target = dayLog.getByteArray();
if (index < 0) {
index = -index;
int num = days.getNumRecords();
Search WWH ::




Custom Search