I seem to have a frustrating problem - an element of my arraylist is overwritten. I have looked at many posts in many forums, but I have not managed to solve it. :chomp:
In my program (which is actually a FBDK function block algorithm implemented in Java), I want to store the data of an input variable (PART) into an element of an out variable array (PART_array). This process will happen multiple times (with the occurence of an event) and must thus store the variable in several array elements.
The problem is that the elements of PART_array are overwritten by the last entry. For instance, for the first event occurence, PART_array[] = ["1"," "," "," "," "," "]. Then, with the second occurence, instead of PART_array[] = ["1","2"," "," "," "," "], I find PART_array[] = ["2","2"," "," "," "," "] - thus showing the overwrite. I have realised that overwrite already occurs with the storage to PART_ARRAY ArrayList. I thought that by reinitializing (p = new Part()) the problem would be solved...obviously not.
Any help in solving this problem will be GREATLY appreciated! The code is as follows:
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
}
}
}
The class file for Part is as follows:
public class Part {
WSTRING part;
void setPart(WSTRING part) {
this.part = part;
}
WSTRING getPart() {
return part;
}
}