2010-09-11 66 views
2

我正在嘗試編寫將N個數組轉換爲N行多維數組的代碼。我目前有一個代碼可以將2個數組變成2行的多維數組。但是,我不確定如何修改它以使此代碼佔用N個數組。取N個數組並將其變爲N行的多維數組JAVA

此外我的代碼目前只能使用相同大小的數組。但是,它需要能夠採用不同長度的數組。這將導致我的多維數組中的行不總是等長。我被告知這意味着列表可能比數組更適合。但是我不熟悉列表。

這裏是我的代碼,因爲它目前爲:提前

public class test5 { 
    int [][] final23; 

public int [][] sum(int [] x, int[] y) 
{ 
final23= new int[2][x.length]; 
for (int i = 0; i < Math.min(x.length, y.length); i++) 
{ 

    final23 [0][i] = x[i]; 
    final23 [1][i] = y[i]; 
} 
return final23; 
} 

public void print() 
{ 
for (int i = 0; i < final23.length; i++) 
{ 
    for (int j = 0; j<final23[0].length; j++) 
    { 

     System.out.print(final23[i][j]+" "); 
    } 
    System.out.println(); 
} 
} 




public static void main(String[] args) 
    { 
     int l[] = {7,3,3,4}; 
     int k[] = {4,6,3}; 
     test5 X = new test5(); 

     X.sum(k,l); 
     X.print(); 
    } 
} 

感謝。對不起,我是剛剛接觸Java並剛剛學習。

+0

爲什麼不學習集合?這將比修改固定長度數組容易得多 – TheLQ 2010-09-11 03:11:01

回答

1
import java.util.Arrays; 
class Arr 
{ 
public static void main(String[] args) 
{ 
int[][] ar=toMulti(new int[]{1,2},new int[]{1,2,3},new int[]{5,6,7,8}); 
System.out.println(Arrays.deepToString(ar)); 

/*OR You can directly declare 2d array like this if your arrays don't 
come as user inputs*/ 
int[][] arr={{1,2,3},{1,2},{3,4}}; 
    System.out.println(Arrays.deepToString(arr)); 
}  
    /* ... is known as variable argument or ellipsis. 
     int[] ... denotes that you can give any number of arguments of the type int[] 
     The function input that we get will be in 2d-array int[][].So just return it.*/ 
    public static int[][] toMulti(int[] ... args) { 
    return args; 

} 
} 
+0

這段代碼只是返回2d數組中的引用。但是如果你需要它作爲副本,那麼你最好遵循Steve的代碼。不同之處在於,如果你在1d數組中做任何改變它也會在二維數組中反映出來,反之亦然。但是,如果你處理巨大的數組,這將更快並且使用更少的內存。 – Emil 2010-09-11 09:34:50

1

由於它們的長度可能不相等,因此您必須考慮矩陣上的死點,可能使用的是Null Object pattern。將每個元素初始化爲一個可以統一處理的特殊情況,就像任何其他元素一樣。

這是我的建議,就如何用數組來完成。 Collections aren't hard雖然。

1

java中的多維數組的大小並不相同 - 它們只是一排排列在數組中的數組,就像任何其他對象一樣。如果您希望它們的大小相同,則必須找到最大大小,並用某種空白或默認值填充較小的數組。

在任何情況下,因爲要複製陣列的一些N多的,只要你接受不同的長度,爲什麼不使用可變參數:

public static int[][] toMulti(int[] ... args) { 
// you can't resize an array, so you have to size your output first: 
int[][] output = new int[args.length][]; 
for (int i =0; i<args.length; i++) 
{ 
    output[i[=args[i].clone(); 

    //you could also do this copying 1 at a time, or with 
    int[] arr =new int[args[i].length]; 
    System.arraycopy(args[i], 0, arr, 0, args[i].length); 
    output[i]=arr; 
} 

如果你想大小他們都具有相同的尺寸System.arraycopy會更好,因爲您將以最大大小創建數組,其餘值將自動爲0(或對於對象數組爲空)。

相關問題