Reputation: 21
I want to store arrays in an array, but I don't know exactly how to do it.
What I want is: I have an array called, for example, array.
In a method I want to append an item to this array, this item would be an array too.
For example, this would be in my first array: (every item of it is appended when the method is called)
{1,2},{2,3},{5,6}
Thanks.
Upvotes: 2
Views: 271
Reputation: 134207
To work purely with arrays, see: http://www.ensta.fr/~diam/java/online/notes-java/data/arrays/arrays-2D-2.html
For example, to allocate everything you might do:
int[][] tri;
//... Allocate each part of the two-dimensional array individually.
tri = new int[10][]; // Allocate array of rows
for (int r=0; r < 2; r++) {
tri[r] = new int[2]; // Allocate a row
}
However, if you need to support an append operation you are better off using another data structure such as List, ArrayList, etc to hold the top-level "array". That way you can just append arrays to it instead of having to play games re-allocating it. Sean's solution is a good fit for this.
Upvotes: 5
Reputation: 66886
void append(List<int[]> arrays) {
int[] newItem = ...;
arrays.add(newItem);
}
...
List<int[]> arrays = new ArrayList<int[]>();
...
// then call append() to do your appending
append(arrays);
...
// now get the array of arrays out of it
int[][] as2DArray = arrays.toArray(new int[0][]);
Upvotes: 1