2016-11-13 33 views
0

我想創建一個節點,它包含一個int數組,它的大小由作爲參數的int值確定,這是我迄今爲止所做的。它工作得很好,但是當我去填充它時,它會使用任何大小的數組,這不是我想要的。謝謝。如何創建一個數組,其大小和內容都是參數?

public Node(int size, int [] contents, Node<T> t) { 
    size = size; 
    intArray = new int[size]; 
    intArray = contents; 
    tail = t; 
    } 
+0

您需要刪除'intArray =內容;'遍歷'在'intArray' – iNan

+0

contents'陣列和設定值不分配內容intArray。使用System.arraycopy複製內容。還要在複製之前驗證陣列大小是否匹配。 – Quagaar

+1

您也可以使用System.arraycopy()而不是遍歷數組。 http://stackoverflow.com/questions/5785745/make-copy-of-array-java – qwerty

回答

0

所以在這裏......

intArray = new int[size]; 
intArray = contents; 

你是第一個初始化數組變量到你想要的大小的數組,但你重新分配數組變量傳遞進來的數組作爲論據。您需要以某種方式複製或截斷傳入的數組。請參閱[System.arraycopy][1]。你可以這樣做......

intArray = new int[size]; 
System.arraycopy(contents, 0, intArray, 0, size); 
相關問題