1

I'm trying to populate a list with string arrays but the only array that is added to the list is the last added. And this seems to be added to all list elements.

What am I doing wrong?

String[] indata = new String[2];
List<String[]> ls = new ArrayList<String[]>();
indata[0]="test1";
indata[1]="test2";
ls.add(indata);
indata[0]="test3";
indata[1]="test4";
ls.add(indata);
for(int index=0; index < ls.size(); index++)
        System.out.println("ZZZZZZZZZZZZ----->>  " + index + "     " + Arrays.toString(ls.get(index)));

Expected output:

ZZZZZZZZZZZZ----->>  0     [test1, test2]
ZZZZZZZZZZZZ----->>  1     [test3, test4]

Actual output:

ZZZZZZZZZZZZ----->>  0     [test3, test4]
ZZZZZZZZZZZZ----->>  1     [test3, test4]
2
  • You need to create new String array for every array added into the List Commented Feb 14, 2013 at 9:17
  • Shorthand way to write, if you are adding literal string. ideone.com/bonDwJ Commented Feb 14, 2013 at 9:24

2 Answers 2

3

Should be:

String [] indata = new String [2];
List <String []> ls = new ArrayList <String []> ();
indata [0] = "test1";
indata [1] = "test2";
ls.add (indata);
indata = new String [2]; // This line added
indata [0] = "test3";
indata [1] = "test4";
ls.add (indata);

When you do ls.add (indata) a reference to your array is stored in the list, but not the copy of the array. So after this both, ls.get (0) and indata points to the same instance of array, and modifying first element this array with indata [0] = "test3" will change what you see using ls.get (0)[0].

Sign up to request clarification or add additional context in comments.

Comments

0

When you create an object and add it to a list, the object is not getting copied to list.Instead a reference of existing object is getting added to list.So when you do this:

String[] indata = new String[2];
List<String[]> ls = new ArrayList<String[]>();
indata[0]="test1";
indata[1]="test2";
ls.add(indata);

Both indata and ls.get(0) are pointing to the same object.

Here you are again modifying the data pointed to by indata to add second array.So ls.get(0) also point to the updated data.

Inorder to add new array, you need to create new array and add it to list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.