2014-01-18 51 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