Reputation: 39
I have this code:
Object [] array=new Object array [5];
array[0]= new Object[3];
array[1]=new Object [10];
array[2]=new Object [7];
...
How can I access the 5th element of array[1]. If it was a 2D array I would say:
Object o=array [1][5];
but I don't want 2D array because I don't want to waste memory since the size varies from array to array.
It would be great if someone could answer me this question..
Btw I don't want to use vectors etc...
Thank you
Upvotes: 2
Views: 7994
Reputation: 5944
You could do it like this:
//This creates a 5 by ? array
Object[][] array = new Object[5][];
array[0] = new Object[3];
array[1] = new Object[10];
array[2] = new Object[7];
....
edit (thanks to the commenters) :
array
is an array of arrays. Each element in array
refers to an array of Objects.
The memory is not wasted on having more elements than needed.
It will look like this
[a00][a01][a02]
[a10][a11][a12][a13][a14][a15][a16][a17][a18][a19]
[a20][a21][a22][a23][a24][a25][a12]
If you now would like to access the 6th element of the 2nd array you would do this:
Object myObj = array[1][5];
Upvotes: 6