2

I have list of type String[] in which add arrays inside a loop that runs n times.

String[] parsedFields = new String[fieldsToParse.length];
List<String[]> myList= new ArrayList<String[]>();

while (getType()) {
    // ...
    for (int i = 0; i < fieldsToParse.length; i++) {
        if (name.equals(fieldsToParse[i])) {
parsedFields[i] = fieldsToParse;
// ...
        }
    }
    myList.add(parsedFields);
}

Every time an array is added to list the array is same but values are different.

The issue is every time I add an array in new iteration all previously added arrays in the list gets update according to the content of last array added.

For e.g. at first iteration myList contains:

myList > array > [0] = [1, 1, 'A']

at second iteration the list will become:

myList > array > [0] = [2, 2, 'B']
myList > array > [0] = [2, 2, 'B']

and at third it will:

myList > array > [0] = [3, 3, 'C']
myList > array > [0] = [3, 3, 'C']
myList > array > [0] = [3, 3, 'C']

And when the while loop breaks, all the array elements in the list contains same arrays (which is actually the last array added). How can I stop it from updated previously added arrays?

halfer
  • 19,824
  • 17
  • 99
  • 186
Maven
  • 14,587
  • 42
  • 113
  • 174

2 Answers2

3

Move the declaration of parsedFields to inside the while loop. otherwise you are just updating the same array and makes a new reference in myList to point to it.

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

while (getType()) {

    String[] parsedFields = new String[fieldsToParse.length];
    // …

    for (int i = 0; i < fieldsToParse.length; i++) {
        if (name.equals(fieldsToParse[i])) {
            parsedFields[i] = fieldsToParse;
// ...
        }
    }
    myList.add(parsedFields);
}
hasan
  • 23,815
  • 10
  • 63
  • 101
1

You need to create a new array each time around the loop - you only ever create one at the moment. Just move the declaration of parsedFields inside the loop.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64