2014-01-18 55 views
0

下面的程序產生10雙一定大小的隨機數,並將它們存儲在一個ArrayList名爲測試 -顯示ArrayList內容<int[]>

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.Random; 

public class randomGenerate 
{ 
    static ArrayList<String> tcase=new ArrayList<String>(); 
    static ArrayList<int[]> test=new ArrayList<int[]>(); 

    public static void main(String args[]) 
    { 

     tcase.add("1"); 
     tcase.add("2"); 
     tcase.add("3"); 
     tcase.add("4"); 
     tcase.add("5"); 
     tcase.add("6"); 
     randomSelection(10,2); 
     for(int i=0;i<test.size();i++) 
     { 
      System.out.println(Arrays.toString(test.get(i))); 
     } 
    } 

    static int randomNo(int max,int min) 
    { 
     Random obj = new Random(); 
     int n = max - min + 1; 
     int i = obj.nextInt(n); 
     int randomNum = min + i; 
     return randomNum; 
    } 

    static void randomSelection(int limit, int pairSize) 
    { 
     int max = Integer.parseInt(Collections.max(tcase)); 
     int min = Integer.parseInt(Collections.min(tcase)); 
     System.out.println(max+" "+min); 
     int ar[]=new int[pairSize]; 
     for(int i = 0;i < limit;i++) 
     { 
      for(int j = 0;j < pairSize;j++) 
      { 
       ar[j]=randomNo(max,min); 
       System.out.print(ar[j]); 
      } 
      test.add(ar); 
      System.out.println(); 
     } 

    } 
} 

我的問題是,雖然打印ArrayList內容「測試」只顯示最後一個值。爲什麼它不顯示所有的值。

輸出 - (例如)

23 
65 
45 
63 
12 
23 
52 
52 
16 
12 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
[1, 2] 
+0

你是什麼意思最後的價值? –

+0

從示例[1,2]被添加到arrayList「test」中的第9個位置。顯示arrayList的內容時只使用for循環[1,2]顯示 – Sashank

回答

6

你總是修改和添加相同的陣列到列表在每次迭代。

,想出這樣的情況:

enter image description here

您需要創建在每次迭代的新數組:

for(int i = 0;i < limit;i++){ 
    int ar[]=new int[pairSize]; //create a new one at each iteration 
    for(int j = 0;j < pairSize;j++){ 
     ar[j]=randomNo(max,min); 
     System.out.print(ar[j]); 
    } 
    test.add(ar); 
    System.out.println(); 
} 
0

的問題是,您要添加的陣列arArrayListrandomSelection()中測試每次迭代,因此當您在下一次迭代中修改ar時,您正在修改它在ArrayList之內,以解決這個問題的嘗試:

方法1:

創建一個新的陣列中的每個迭代

int ar[]; 
for (int i = 0; i < limit; i++) { 
    ar = new int[pairSize]; // Initialize inside 'for' 
    for (int j = 0; j < pairSize; j++) { 
     ar[j] = randomNo(max, min); 
     System.out.print(ar[j]); 
    } 
    test.add(ar); 
} 

方式2:

創建陣列ar的副本,並將其添加到test

int ar[] = new int[pairSize]; 
for (int i = 0; i < limit; i++) { 
    for (int j = 0; j < pairSize; j++) { 
     ar[j] = randomNo(max, min); 
     System.out.print(ar[j]); 
    } 

    test.add(ar.clone()); // Create a copy 
} 
+0

謝謝@ZouZou。鄒鄒說明真的有幫助。 – Sashank

+0

謝謝@Christian。你們就像超級電腦 – Sashank