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