简体   繁体   中英

How to handle multidimensional array?

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.

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.

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][]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM