Java Reference
In-Depth Information
}
public int getTime (int index) {
return ((Entry) entries.elementAt (index)).time;
}
public int getValue (int index) {
return ((Entry) entries.elementAt (index)).value;
}
Finally, we add a method for deleting an entry. The method takes a point of time as input and removes
the best matching entry:
public void remove (int time) {
int bestDelta = 24;
int bestIndex = -1;
for (int i = 0; i < entries.size(); i++) {
int delta = Math.abs (time - getTime (i));
if (delta < bestDelta) {
bestDelta = delta;
bestIndex = i;
}
}
if (bestIndex != -1) {
entries.removeElementAt (bestIndex);
}
}
Serialization and Deserialization for Persistent Storage
Because the DayLog is intended to be stored persistently, conversion methods from and to byte arrays
are necessary. As described in Chapter 5 , "Data Persistency," we use a ByteArrayInputStream
for deserialization and a ByteArrayOutputStream for serialization:
public DayLog (byte [] data) throws IOException {
DataInputStream dis = new DataInputStream
(new ByteArrayInputStream (data));
date = dis.readInt();
int count = dis.readInt();
for (int i = 0; i < count; i++) {
Entry entry = new Entry();
entry.time = dis.readInt();
entry.value = dis.readInt();
entries.addElement (entry);
}
dis.close();
}
public byte [] getByteArray() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream (bos);
Search WWH ::




Custom Search