2010-02-24 35 views
2

我想将数组存储在一个数组中,但我不知道如何去做。我想要的是: 我有一个数组,例如数组。如何处理多维数组?

在我想追加一个项目到这个数组的方法中,这个项目也是一个数组。

例如,这将是在我的第一阵列:(当该方法被称为它的每一个项被追加)

{1,2},{2,3},{5,6} 

感谢。

回答

5

要使用数组纯粹的工作,请参阅:http://www.ensta.fr/~diam/java/online/notes-java/data/arrays/arrays-2D-2.html

例如,分配一切你可以做:

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 
} 

不过,如果你需要支持附加操作,你最好使用其他数据结构,如List,ArrayList等来保存顶层的“数组”。这样,您可以将数组附加到它上面,而不必再玩游戏重新分配它。肖恩的解决方案非常适合这一点。

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

谢谢,我还有1个问题:如何检查数组是否已经在主数组中? – Robert 2010-02-24 20:12:50

+0

通过调用arrays.contains(theIntArray); 如果您想确保主集合中没有重复条目,请使用LinkedHashSet而不是ArrayList。 LinkedHashSet维护顺序并且不允许重复条目。 ArrayList维护顺序,但允许重复条目。 – 2010-02-24 22:01:51