2011-12-11 77 views
1

我正在嘗試學習Java,但是在將數組傳遞給構造函數時遇到了問題。 例如:如何將數組傳遞給構造函數?

應用類: byte[][] array = new byte[5][5]; targetClass target = new targetClass(array[5][5]);

目標類:

public class targetClass { 
    /* Attributes */ 
    private byte[][] array = new byte[5][5]; 

    /* Constructor */ 
    public targetClass (byte[][] array) { 
     this.array[5][5] = array[5][5]; 
    } 

} 

我會非常感激,如果你能告訴我怎樣才能做到這一點。

+0

既然你學習Java的類名應該總是以大寫字母開頭。 – Bhushan

回答

5

首先,通常在Java類的名字開頭大寫,現在,你遇到的問題,它應該是:

public class TargetClass { /* Attributes */ 
    private byte[][] array; 

    /* Constructor */ 
    public TargetClass (byte[][] array) { 
     this.array = array; 
    } 
} 
+0

甜。謝謝! 我還有很多東西需要學習。 – bbalchev

+0

@BlagovestBalchev那是最棒的部分! :) – MByD

1

在你的應用程序類,下面應該工作:

byte[][] array = new byte[5][5]; 
TargetClass target = new TargetClass(array); // Not array[5][5] 

此外,爲您的目標類,下面應該工作:

public class TargetClass { 
    /* Attributes */ 
    private byte[][] array; // No need to explicitly define array 

    /* Constructor */ 
    public TargetClass (byte[][] array) { 
     this.array = array; // Not array[5][5] 
    } 
} 

如前所述,類名通常是大寫,所以這就是我對你的班名所做的。

2

你並不需要在申報的時候並初始化類中的數組。它可以設置爲傳遞數組的引用。例如,

public class targetClass { 
    /* Attributes */ 
    private byte[][] array = null; 

    /* Constructor */ 
    public targetClass (byte[][] array) { 
     this.array = array; 
    } 

} 
0

我會假設你想給私人數組分配給數組傳遞的,而不是試圖挑5,5元了傳入的數組。

構造內部,語法應爲:

this.array =陣列;

在應用時,它應該是

targetClass目標=新targetClass(數組);

1
public class targetClass { 
    /* Attributes */ 
    private byte[][] array = null; 

    /* Constructor */ 
    public targetClass (byte[][] array) { 
     this.array = array; 
    } 

} 

然後調用它像這樣

byte[][] array = new byte[5][5]; 
targetClass target = new targetClass(array);