如何在 Java 中扩展多维数组?
我需要扩展它的第一个维度。它的格式如下:
myArray[x][7]
“7”将在所有扩展部分保持“7”。
最佳答案
Java 中的数组具有固定长度,因此您无法真正扩展它。您必须创建一个更大的新数组,然后将旧数组的内容复制到新数组中。像这样:
public class Test {
public static void main(String[] args) {
int[][] myArray = new int[3][7];
// Print first dimension
System.out.println(myArray.length); // prints 3
myArray = addRow(myArray);
// Print first dimension
System.out.println(myArray.length); // prints 4
}
private static int[][] addRow(int[][] previous) {
int prevRowCount = previous.length;
int[][] withExtraRow = new int[prevRowCount + 1][];
System.arraycopy(previous, 0, withExtraRow, 0, previous.length);
withExtraRow[prevRowCount] = new int[] { 1, 2, 3, 4, 5, 6, 7 };
return withExtraRow;
}
}
您当然也可以使用例如 ArrayList<SomeType[]>
动态增长。 (这实际上是处理动态增长数组时的首选方式。)
import java.util.*;
public class Test {
public static void main(String[] args) {
List<int[]> myArray = new ArrayList<int[]>();
// Print first dimension
System.out.println(myArray.size()); // prints 0
// Add three rows
myArray.add(new int[] { 1, 2, 3, 4, 5, 6, 7 });
myArray.add(new int[] { 11, 12, 13, 14, 15, 16, 17 });
myArray.add(new int[] { 21, 22, 23, 24, 25, 26, 27 });
// Print first dimension
System.out.println(myArray.size()); // prints 3
}
}
关于java - 在 Java 中扩展多维数组 (2D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4361253/