function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mattdarnoldmattdarnold 

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

And, instead I get:
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++) {
    xd.add(0);
   }
   d.add(xd);
   d[i][0] = i;
  }
  
  System.debug(d);
  
  return 'Success';
 }
 
 String ma = createArray();

 



Message Edited by mattdarnold on 10-21-2008 09:56 AM
Best Answer chosen by Admin (Salesforce Developers) 
mattdarnoldmattdarnold
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

All Answers

philbophilbo
Hey,

You're adding the same array 'xd' six times to your 2-D array 'd'.  So when you go 'd[ i ][ 0 ] = i;', you are hitting that single 'xd' array each time, and updating its zero'th element  Think of 'd' as an array of ARRAY REFERENCES, in your case with each array ref pointing at the same 'xd' array.  

Presumably this is not what you want  :^}  ... just put that 'List<Integer> xd = new List<Integer>();' statement inside the loop over 'i', and remove the 'xd.clear();' statement altogether; that oughta do it.
mattdarnoldmattdarnold
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
This was selected as the best answer