如何从旧数组创建一个新数组?

时间:2013-05-12 10:18:03

标签: java

float[][] pesIAlcada = {
        { 2.4f, 3.1f, 3.07f, 3.7f, 2.7f, 2.9f, 3.2f, 3f, 3.6f, 3.1f },
        { 19f, 18.7f, 22f, 24f, 17f, 18.5f, 21f, 20f, 18.7f, 22f, 18f },
        { 47f, 48f, 49f, 50f, 51f, 52f, 51.5f, 50.5f, 49.5f, 49.1f, 50f },
        { 101f, 104f, 106f, 107f, 107.5f, 108f, 109f, 110f, 112f, 103f } };
/* 
 * I already created an array. And I want to make a new one but some
 * infomation from the old array. How can I do, plz?
 */
float[][] pesNeixement = new float[ROWS][COLS];
for (int i = 0; i < 2; i++) {
    for (int j = 0; j < pesIAlcada[i].length; j++) {
        System.out.print(pesIAlcada[i][j]);
    }
}

4 个答案:

答案 0 :(得分:1)

使用此功能深层复制二维数组。

public static float[][] deepCopy(float[][] original, Integer offset, Integer numberOfRows) {
    if (original == null) {
        return null;
    }
    if (offset == null) {
        offset = 0;
    };

    if (numberOfRows == null) {
        numberOfRows = original.length;
    };

    final float[][] result = new float[numberOfRows - offset][];
    for (int i = offset; i < numberOfRows; i++) {
         result[i] = Arrays.copyOf(original[i], original[i].length);
    }
    return result;
}

在您的代码中:

float[][] pesNeixement = deepCopy(pesIAlcada, 0, 2);

答案 1 :(得分:0)

这取决于您对“某些信息”的定义。如果要将数组的一部分复制到新数组,则可以使用System.arraycopy

示例

int[] numbers = {4,5,6,7,8};
int[] newNumbers = new int[10];

System.arraycopy(numbers,0,newNumbers,0,3);

答案 2 :(得分:0)

如果要在新数组(pesIAlcada)中复制pesNeixement中的某些行,可以使用以下内容:

int fromRow = 0;     // Start copying at row0 (1st row)
int toRow = 2;       // Copy until row2 (3rd row) <- not included
                     // This will copy rows 0 and 1 (first two rows)
float[][] pesNeixement = new float[toRow - fromRow][];

for (int i = fromRow; i < toRow; i++) {
    pesNeixement[i] = new float[pesIAlcada[i].length];
    System.arraycopy(pesIAlcada[i], 0, pesNeixement[i], 0, pesIAlcada[i].length);               
}

另见 short demo

答案 3 :(得分:0)

System.arrayCopy()是从现有数组创建新数组的有效方法。您可以使用此功能完成自己的编码。探索