-1

So what I'm trying to do is to add an array of strings to my Arraylist BDDvars. The issue I seem to be facing is that after adding 'temp' (which is an array of strings) to the BDDvars list, when I instantly print -- I get values. However, after reinitializing temp, somehow the values that were present in my arraylist are also reset. Would appreciate some help on why this is happening. Thanks!

Code is here:

    List<String[]> BDDvars =new ArrayList<String[]>();

    BDDvars.add(temp);
    System.out.println(BDDvars.get(0)[0]); // this gives value of temp
    for(int n =0;n<11;n++)
      temp[n] = "";
    System.out.println(BDDvars.get(0)[0]); // this gives empty string - why?

1 Answers1

2

When you add temp to BDDvars you're not creating a new array. Instead both temp and an element in BDDvars are using the same reference.

Make a copy of the array first if you want to modify temp without modifying the value in BDDvars:

String[] tempCopy = new String[temp.length];
System.arraycopy( temp, 0, tempCopy, 0, temp.length);
BDDvars.add(tempCopy);

EDIT

or use clone

BDDvars.add(temp.clone());
flakes
  • 21,558
  • 8
  • 41
  • 88