-3

我似乎遇到了一个令人沮丧的问题——我的数组列表的一个元素被覆盖了。我在很多论坛上看了很多帖子,但我没有设法解决它。:chomp:

在我的程序(实际上是用 Java 实现的 FBDK 功能块算法)中,我想将输入变量(PART)的数据存储到输出变量数组(PART_array)的元素中。这个过程将发生多次(随着事件的发生),因此必须将变量存储在几个数组元素中。

问题是 PART_array 的元素被最后一个条目覆盖。例如,对于第一个事件发生,PART_array[] = ["1"," "," "," "," "," "]。然后,第二次出现,而不是 PART_array[] = ["1","2"," "," "," "," "],我发现 PART_array[] = ["2","2", " "," "," "," "] - 从而显示覆盖。我已经意识到存储到 PART_ARRAY ArrayList 时已经发生了覆盖。我认为通过重新初始化 (p = new Part()) 问题将得到解决......显然不是。

任何解决此问题的帮助将不胜感激!代码如下:

public class STORE_TO_ARRAY extends fb.rt.FBInstance {

    public ArrayList<Part> PART_ARRAY = new ArrayList<Part>();
    Part p = new Part();

    /** The default constructor. */
    public STORE_TO_ARRAY() {
       super();
    }

    /** ALGORITHM REQ IN Java*/ -- a method called in the program
    public void alg_REQ() {
        int ct = 0;
        ct = current_task;
        if (ct <= NumOfTasks) {
            //write received input data to output variable array elements
            //this is where the problem occurs!!!!
            p.setPart(PART); //set value of Part
            PART_ARRAY.add(ct-1,p); //adding to arraylist
            Part p = new Part(); //trying to reinitialise the object    
        }
    }
}

Part的类文件如下:

public class Part {
    WSTRING part;
    void setPart(WSTRING part) {
        this.part = part;
    }
    WSTRING getPart() {
        return part;
    }
}
4

1 回答 1

0

下面的代码创建一个局部变量(在下一行中,它超出范围并在使用之前消失),而不是为类变量分配一个新值(我假设这是你想要的做)。

Part p = new Part(); //trying to reinitialise the object

尝试将其替换为

p = new Part(); //trying to reinitialise the object

附带说明一下,一个像样的 IDE(如 NetBeans)应该会警告您创建隐藏类变量的局部变量。

于 2012-11-27T12:16:36.087 回答