EDIT: I am rewriting this question, to hopefully make the code more explicit.
I have a class, Pred, with 2 variables.
public class Pred {
private String str;
private ArrayList<Keys> keysArr;
public Pred(String s) {
this.str = s;
keysArr = new ArrayList<Keys>;
}
public void setKeysArr(ArrayList<Keys> kArr) {
this.keysArr.addAll(kArr);
}
}
In the extract() method, I loop through another array, get some variables, and use these to make new Preds.
public static Collection<Pred> extractPause(Keys[] kseArr) {
Collection<Pred> predArray = new ArrayList<Pred>();
// create method variables
ArrayList<Keys> keysArray ka = new ArrayList<Keys>();
String s = "";
// loop through an array
for (int i; i < someArray.size(); i++) {
s = "Sam"+i;
ka.add(key1+i);
ka.add(key2+i);
// create new instance of Pred
Pred p = new Pred(s);
p.setKeysArr(ka);
predArray.add(p);
// reset variables (not sure if that's necessary)
s = "";
ka.clear();
}
return predArray;
}
When I go to print the array of Preds, I run into a weird situation, where I’m getting the array values of only the last Pred in the predArray.
public void print() {
for (Pred p : predArry)
System.out.println(p.str+" "+p.get(p.keysArr.size()-1).getKeys());
}
Output:
Sam1 key12 key2
Sam2 key12 key22
Should be:
Sam1 key11 key21
Sam2 key12 key22
Probably because when you create your list of
Fooinstances, you doinstead of doing
Remember that a list contains references to objects, and not copies of objects. So if you add the same Foo instance 10 times to the list, the list will contain 10 references to this unique instance, which will of course contain its last modified state.