我收到了这个我无法想象的错误。我有一个接收器类接收数据包,其中是一个ArrayList。不,数据包没有ArrayList;班上有一个。当我收到一个新数据包时,ArrayList会被更改,但在我更改它之前。事实上,在我甚至从包中读取数据到我正在使用数据的对象之前。不仅如此,ArrayList还将数组中的所有对象更改为相当于在后面的指令中根据数据创建的对象...
产生奇怪行为的方法:
public void processPackets() {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
while(true) {
System.out.println("Start: " + outBuffer);
socket.receive(packet);
System.out.println("Before: " + outBuffer);
// Find out where the packets are coming from
if (sendHost == null) {
sendHost = packet.getAddress();
sendPort = packet.getPort();
}
// Grab the data from the packet
PacketInfo data = new PacketInfo(packet.getData());
System.out.println("Found: " + data);
if (this.packetWithinWindow(data.getSequenceNumber())) {
outBuffer.add(data);
System.out.println("After: " + outBuffer);
}
ackThePacket(data);
if (processData()) {break;}; // Returns true after last packet processed
System.out.println("End: " + outBuffer);
}
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}
鉴于outBuffer是ArrayList<PacketInfo>
并且PacketInfo.toString()
返回序列号和前20个字节的列表,这是一个奇怪行为的样本,然后打印到控制台(几个之后)循环遍历outBuffer开始为空的代码:
Start: []
Before: []
Found:
2 [-120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120]
After: [
2 [-120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120]]
End: [
2 [-120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120]]
Start: [
2 [-120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120, 8, 0, 2, -120]]
Before: [
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48]]
Found:
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48]
After: [
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48],
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48]]
End: [
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48],
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48]]
Start: [
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48],
1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 65, 0, 76, 0, 71, 68, 70, 68, 48]]
Before: [
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Found:
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
After: [
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
End: [
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
4 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
这令我感到困惑,所以任何帮助都会受到赞赏。如果有任何帮助,可以使用Java 6编译。