I'm currently putting together a small client/server pair and I ran into a problem with ArrayLists, which I solved, but want to learn more about. Here's a sample of the code:
public double[] receiveMessage(int messageLength) throws IOException {
// wait for bytes
while (this.getInputStream().available() == 0) {
}
// read bytes
List<byte[]> incomingMessage = new ArrayList<byte[]>();
int byteLength = 8;
byte[] tempByte = new byte[byteLength];
while (this.getInputStream().available() != 0) {
this.getInputStream().read(tempByte, 0, byteLength);
incomingMessage.add(tempByte);
} ............
If I were to print tempByte at each loop iteration, I receive the unique array I expected. But, if I were to print each element of the completed list "incomingMessage", I receive the same array (the last tempByte array) "messageLength" times.
This bug was fixed when I placed the tempByte declaration inside the while-loop and added a tempByte=null after the adding it to the list.
While I'm not a programming expert, what is the reason for the original bug I saw?