Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
mattdarnold

# Help working with 2 dimensional arrays

Hi - I've been working on some code to create a 2 dimensional array or an array of arrays - i.e. List<List<Primitive/Sobject>>, in this case List<List<Integer>>. I've developed some code along with some help from this post that sets up an array then loops through the array generating the internal array, or columns, then adds that array to the containing array thereby generating a row. The issue I am having is that while this works, when I examine the array outside of the for-loop each of the rows contains the same data when it shouldn't.

For example, I expect to generate a matrix containing the following data with the code below:
1,0,0,0,0,0
2,0,0,0,0,0
3,0,0,0,0,0
4,0,0,0,0,0
5,0,0,0,0,0
6,0,0,0,0,0

6,0,0,0,0,0
6,0,0,0,0,0
6,0,0,0,0,0
6,0,0,0,0,0
6,0,0,0,0,0
6,0,0,0,0,0
6,0,0,0,0,0

Here is the code I've been using to test. Any help/advice is greatly appreciated. Try running this in the Execute Anonymous window in the Force IDE or the System Log window.

Code:
``` public String createArray() {
Integer n;
Integer m;
Integer i;
Integer j;
Integer x;
List<List<Integer>> d = new List<List<Integer>>();
List<Integer> xd = new List<Integer>();

n = 6;
m = 5;

for (i=0; i<=n; i++) {
xd.clear();
for (j=0; j<=m; j++) {
}
d[i][0] = i;
}

System.debug(d);

return 'Success';
}

String ma = createArray();```

Message Edited by mattdarnold on 10-21-2008 09:56 AM
mattdarnold
Thanks! That solved my problem. Such a simple fix, but it caused a whole lot of frustration. It is working as expected now. Thanks, again.

-- Matt