日期:2014-05-20  浏览次数:20617 次

一个数组和List的问题
public   List   getScore(){

                List   finalList   =   new   ArrayList();
                String[]   score   =   new   String[2];
                           
                for   (int   i   =   0;   i   <   3;   i++)   {
                        for   (int   j   =   0;   j   <   2;   j++)   {
                                int   k   =   (int)   (Math.random()   *   100);
                                score[j]=Integer.toString(k);
                        }
                        finalList.add(score);
                }

                return   finalList;
}
请问:为什么这个方法返回出来的List里的3个数组的内容是一样的?都是最后一次循环所随即出来的数组.

比如:3次循环所循环出来的数组的数据分别是:11,34     24,54     35,87
但是在finalList里的3个数组都是35,87     为什么呢?


------解决方案--------------------
往LIst中添加的score相当于一个引用,当你要从List中取Score时,它会找到Score的内存地址,然后取值。而不是把Score的内容移植到了List中,所以你虽让三次循环都添加了Score,因为变量名相同,List中记录的地址是相同的,而Score内容在循环过程中已经被覆盖了。
------解决方案--------------------
List finalList = new ArrayList();

for (int i = 0; i < 3; i++) {
String[] score = new String[2];
for (int j = 0; j < 2; j++) {
int k = (int) (Math.random() * 100);
score[j]=Integer.toString(k);
}
finalList.add(score);
}