Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
 
Did you try anything yourself? If you did, you wouldn't have asked that. –  skuntsel Apr 13 '13 at 9:40
 
Create two dimensional array to hold array[array] leepoint.net/notes-java/data/arrays/arrays-2D.html –  Joseph Selvaraj Apr 13 '13 at 20:25
add comment

1 Answer

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];
share|improve this answer
1  
And additionally you can use Object o=array [1][5]; to access elements. –  Lee White Apr 13 '13 at 9:43
1  
Might be worth mentioning that a 2D array is an array of arrays. –  christopher Apr 13 '13 at 9:43
 
Thank you great :) very helpful –  dm_poy Apr 13 '13 at 10:17
 
Glad that I could help. If it solves your problem, can you accept the answer? –  DeltaLima Apr 13 '13 at 11:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.