简体   繁体   English

如何处理多维数组?

[英]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. 我想要的是:我有一个名为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 要纯粹使用数组,请参阅: 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". 但是,如果需要支持附加操作,最好使用其他数据结构(如List,ArrayList等)来保存顶级“数组”。 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][]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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