tags:

views:

73

answers:

2

Hello

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.

+3  A: 

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.

Justin Ethier
+1  A: 
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][]);
Sean Owen
Thanks, and I have 1 more question: how can I check if an array is already in the main array?
Robert
By calling arrays.contains(theIntArray);If you want to be sure there are no duplicates entries in your main collection, use a LinkedHashSet instead of an ArrayList.A LinkedHashSet maintains order and will not allow duplicate entries. An ArrayList maintains order but allows duplicate entries.
Hans Westerbeek