重复数组列表条目 [英] Duplicate Array List Entries

查看:94
本文介绍了重复数组列表条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前组建了一个小的客户端/服务器对,我遇到了一个问题的ArrayList,这是我解决了,但想了解更多有关。这里的code的样本:

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);
    } ............

如果我是在每次循环迭代打印tempByte,我收到了独特的阵列我的预期。但是,如果我要打印完成的名单incomingMessage的每一个元素,我收到相同的数组(最后tempByte阵列)messageLength时代。

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.

当我把while循环里面的tempByte声明,并增加了tempByte =此错误是固定空后,将其添加到列表中。

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?

推荐答案

您修改了同一个字节[] 对象每次。你被替换数组的元素在,而循环,那么你叫

You were modifying the same byte[] object each time. You were replacing the elements of the array in each iteration of the while loop then you called read.

这声明 tempByte 数组内修复该问题的原因是,你现在在创建每个迭代过程中一个新的,独立的字节数组。而不是被添加一个阵列多次,你现在有多个不同的阵列补充说。

The reason that declaring tempByte inside the array fixes the issue is that you are now creating a new, separate byte array during each iteration. Instead of one array being added multiple times, you now have multiple different arrays added.

这篇关于重复数组列表条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆