+ Start a Discussion
Noam Damri 3Noam Damri 3 

initializing a 3 dimension array

Hey everybody.

Ive created a 3 dimension integer array, it's go like this:
List<List<List<integer>>> ArrayList = new  List<List<List<integer>>>();

the thing is that i'm trying to approach cell directly, like that:
ArrayList[2][3][4] = 7;

and im getting:
FATAL_ERROR|System.ListException: List index out of bounds: 2

which i was guessing is because i havnt initialized the cell and tried to approach it directly.

ive run a 3 nested for loops in order to initialize the array using:
ArrayList.add(0);
but i kept getting the same message (this time: List index out of bounds: 0, of course)

so im a bit stuck and dont know how to deal with this array but im surely have to use it

suggestions will be welcomed!

Thanks in advanced,
Noam
Best Answer chosen by Noam Damri 3
Noam Damri 3Noam Damri 3
Just got it. This is how you initalize a 3 dimension array:

public void test(){
        integer d1_size = 5;
        integer d2_size = 20;
        integer d3_size = 4;
       
        list<list<list<integer>>> three_d_array = new list<list<list<integer>>>();
        list<list<integer>> two_d_array = new list<list<integer>>();
        list<integer> one_d_array = new list<integer>();
       
        for(integer i=0 ; i<d3_size ; i++){
            for(integer j=0 ; j<d2_size ; j++){
                for(integer k=0 ; k<d1_size ;k++){
                    one_d_array.add(0);
                }
                two_d_array.add(one_d_array);
            }
            three_d_array.add(two_d_array);
        }               
 }

All Answers

olegforceolegforce
You have to put a value in the array first in order to be able to get something from a position. It seems that you only added one element arrayList.add(0) and trying to access third element ArrayList [2]. 
Noam Damri 3Noam Damri 3
Just got it. This is how you initalize a 3 dimension array:

public void test(){
        integer d1_size = 5;
        integer d2_size = 20;
        integer d3_size = 4;
       
        list<list<list<integer>>> three_d_array = new list<list<list<integer>>>();
        list<list<integer>> two_d_array = new list<list<integer>>();
        list<integer> one_d_array = new list<integer>();
       
        for(integer i=0 ; i<d3_size ; i++){
            for(integer j=0 ; j<d2_size ; j++){
                for(integer k=0 ; k<d1_size ;k++){
                    one_d_array.add(0);
                }
                two_d_array.add(one_d_array);
            }
            three_d_array.add(two_d_array);
        }               
 }
This was selected as the best answer