elements of arraylist duplicated

落爺英雄遲暮 提交于 2019-12-25 03:12:38

问题


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

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++;

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

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.

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

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.

much appreciated

clive


回答1:


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);
}

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);
}

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




回答2:


You haven't posted your code so I have to guess, but it sounds like you're adding the same String[] to your list multiple times and just modifying that single array instance on each iteration of your loop.

You need to make sure that you actually allocate a new array on each iterations. eg: there should be a line something like:

recordArray = new String[size];

inside your loop.



来源:https://stackoverflow.com/questions/5626587/elements-of-arraylist-duplicated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!