arraylist 的元素重复 [英] elements of arraylist duplicated

查看:35
本文介绍了arraylist 的元素重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个数组列表并在 DO While 循环中向它添加了元素(字符串数组).我使用以下内容添加元素:

i have created an arraylist and added elements (string array) to it in a DO While loop. i use the following to add the elements:

tempList.add(recordArray); //- recordArray is a String[]

//ArrayList<String[]> tempList = new ArrayList<String[]>();// is declared in the activity before onCreate method

如果我使用以下代码检查 DO WHILE 循环中的数组:

if i check the array within the DO WHILE loop using following code:

aStringArray = tempList.get(index);
Log.i(TAG,"aStringArray[0] = " + aStringArray[3]);
index++;

我为添加到 arrayList 的 3 个数组元素中的每一个都得到了正确的字符串.

i get the correct string for each of the 3 array elements added to the arrayList.

问题是当我尝试在 DO WHILE 循环之外使用相同的代码时,3 次迭代中的每一次都显示相同的字符串.

the problem is when i try using the same code outside of the DO WHILE loop, the same string is displayed for each of the 3 iterations.

总而言之,在 DO WHILE 循环中,我得到以下结果:

so to sum up, in the DO WHILE loop i get the following:

1st iteration -  aStringArray[3] - displays "100350
2nd iteration -  aStringArray[3] - displays "100750
3rd iteration -  aStringArray[3] - displays "100800

在 DO WHILE 循环之外,我得到以下信息:

outside of the DO WHILE loop i get the following:

1st iteration -  aStringArray[3] - displays "100800
2nd iteration -  aStringArray[3] - displays "100800
3rd iteration -  aStringArray[3] - displays "100800

我到处寻找答案,但找不到.希望这里有人可以提供帮助.

i've searched all over for an answer but can't find one. hope someone here can help.

非常感谢

克莱夫

推荐答案

我强烈怀疑您每次执行循环时都在添加 相同 字符串数组.您应该每次都创建一个 new 字符串数组.

I strongly suspect you're adding the same string array each time you go through the loop. You should create a new string array each time.

不要忘记列表只包含引用.所以我的猜测是你的代码看起来像这样:

Don't forget that the list only contains references. So my guess is that your code looks like this:

ArrayList<String[]> tempList = new ArrayList<String[]>();
String[] recordArray = new String[4];

for (int i = 0; i < 10; i++)
{
    recordArray[0] = "a" + i;
    recordArray[1] = "b" + i;
    recordArray[2] = "c" + i;
    recordArray[3] = "d" + i;
    tempList.add(recordArray);
}

最终得到一个包含 10 个相同引用的 ArrayList.相反,你想要这个:

That ends up with an ArrayList of 10 identical references. Instead, you want this:

ArrayList<String[]> tempList = new ArrayList<String[]>();

for (int i = 0; i < 10; i++)
{
    String[] recordArray = new String[4];
    recordArray[0] = "a" + i;
    recordArray[1] = "b" + i;
    recordArray[2] = "c" + i;
    recordArray[3] = "d" + i;
    tempList.add(recordArray);
}

这样你就可以引用列表中的 10 个不同数组.

That way you have references to 10 different arrays in the list.

这篇关于arraylist 的元素重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆