我目前正在组装一个小型客户端/服务器对,并且遇到了 ArrayLists 的问题,我已解决该问题,但想了解更多信息。这是代码示例:
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);
} ............
如果我在每次循环迭代时打印 tempByte,我会收到我期望的唯一数组。但是,如果我要打印已完成列表“incomingMessage”的每个元素,我会收到相同的数组(最后一个 tempByte 数组)“messageLength”次。
当我将 tempByte 声明放入 while 循环内并在将其添加到列表后添加 tempByte=null 时,此错误已得到修复。
虽然我不是编程专家,但我看到的原始错误的原因是什么?
最佳答案
您每次都修改相同的byte[]
对象。您在 while
循环的每次迭代中替换数组的元素,然后调用 read
。
在数组内声明 tempByte
可以解决该问题,因为您现在在每次迭代期间创建一个新的、单独的字节数组。您现在添加了多个不同的数组,而不是多次添加一个数组。
关于java - 重复的数组列表条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28995533/