Aalto Aalto - 14 days ago 9
Java Question

DataInputStream strange behaviour

I would like to build an hashmap from a binary file. This binary file has the following structure: the first integer indicates the number of integers that I have to read from the stream in order to build the hashmap followed by the key/value pairs.

So for an hashmap with three values I would have a total of 7 Integers:

1 int to read - 2 key - 3 value - 4 key - 5 value - 6 key - 7 value

How is it possible that the two following codes have two different outcomes? The only difference is that in the first example I use an auxiliary variable a to store the value of bytes to read. In the second one I just use it directly in the for loop.

static Int2IntMap fetchHashMap(Int2IntMap map, DataInputStream DIS) throws IOException {
int a = DIS.readInt();
for (int i = 0; i < a; i++) {
map.put(DIS.readInt(),DIS.readInt());
}
return map;
}


This is the code without auxiliary variable:

static Int2IntMap fetchHashMap(Int2IntMap map, DataInputStream DIS) throws IOException {
for (int i = 0; i < DIS.readInt(); i++) {
map.put(DIS.readInt(),DIS.readInt());
}
return map;
}


The former works better than the latter but it is still inconsistent with the structure I would expect.

I do not know if it is relevant but my implementation uses multi-threading, but each thread has its own DataInputStream.

qxz qxz
Answer

The entire condition of a for loop is executed before every iteration. In your second method, i < DIS.readInt(); runs before each iteration, reading a new int from DIS. Your first method does it the correct way, by only reading once and caching the value.