2017-02-13 65 views
-2

我在理解數組是如何工作的時候遇到了一些麻煩,特別是當數組沒有被賦予特定的大小時。例如,如果我給出的代碼:JAVA:創建一個具有相同數量的行/列參數的新數組?

public int [][] someMethodHere(int [][] myNewArray) { 
//code here 
} 

我想知道我怎麼可以創建在參數相同的行數和列的方法中的另一個數組(不只是一些數值增加在參數中,然後只是在新的數組中寫入相同的值。謝謝!)

+3

您只需獲得數組的長度,性能和用途它在製作新陣列時。 –

+1

這是一維數組; 「行和列」是什麼意思? – ajb

+0

對不起,我忘了添加在另一個支架 – EyeOfTheOwl

回答

-1

您可以複製數組並清除新數組。

public static int[][] someMethodHere(int[][] src) { 
    int length = src.length; 
    int[][] target = new int[length][src[0].length]; 
    for (int i = 0; i < length; i++) { 
     System.arraycopy(src[i], 0, target[i], 0, src[i].length); 
     Arrays.fill(target[i], 0); 
    } 
    return target; 
} 
+0

這創建了一堆空行,沒有列。 – shmosel

+0

現在它變得更沒有意義了。您正在創建一個乾淨的數組,然後從源數組中複製數據並立即清除它。 – shmosel

0

數組具有您在創建陣列時設置的固定大小。

這與許多其他數據結構(如ListMap)是不同的,它們是「智能」的,可以在需要時自行調整大小。

所以,當你創建一個數組,你必須告訴編譯器,它有多大:

// create the original array with 10 slots 
int[] originalArray = new int[10]; 

如果你想創建一個同樣大小的新數組,你可以使用Array類型的length財產。

// create a new array of the same size as the original array 
int[] newArray = new int[originalArray.length]; 

在你的二維陣列的情況下,你可以做這樣的:

// create the original array 
int[][] originalArray = new int[10][20]; 

// create a new array of the same size as the original array 
int[][] newArray = new int[originalArray.length][originalArray[0].length]; 

注意,指定第二尺寸的長度時,我得到的第一個元素的長度在原始數組中。只要所有的行具有相同的長度,這就可以工作。

如果行的長度不同,你可以通過遍歷數組這樣的第一個維度設置新的陣列中的每一行的長度:

// create a new array where the first dimension is the same size as the original array 
int[][] newArray = new int[originalArray.length][]; 

// set the size of the 2nd dimension on a per row basis 
for(int i = 0; i < originalArray.length; i++) { 
    newArray[i] = new int[originalArray[i].length]; 
} 
相關問題