扩展多维数组(2D)

时间:2010-12-05 21:18:24

标签: java multidimensional-array extension-methods

如何在Java中扩展多维数组?
我需要扩展它的第一个维度。它的格式如下 myArray[x][7]
7将在所有扩展部件上保持7个。

4 个答案:

答案 0 :(得分:3)

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

    }
}

答案 1 :(得分:1)

您也可以使用Arrays.copyOf方法,例如:

import java.util.Arrays;

public class Array2D {
    public static void main(String[] args) {
        int x = 5 //For example
        int[][] myArray = [x][7];

        myArray = Arrays.copyOf(myArray, myArray.length + 1); //Extending for one
        myArray[myArray.length - 1] = new int[]{1, 2, 3, 4, 5, 6, 7};
    }
}

答案 2 :(得分:0)

如果你想这样做,请创建一个包含数组作为实例变量的类,并处理与它的所有交互。

答案 3 :(得分:0)

你不能。

您可以创建一个具有正确尺寸的新数组,但我建议您阅读有关ArrayList类的信息(据您所知),它允许使用动态数组。