读书人

一个数组和List的有关问题

发布时间: 2011-12-02 23:47:57 作者: rapoo

一个数组和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);
}

读书人网 >J2SE开发

热点推荐