简体   繁体   中英

value change in ith element influences value in the 0th element for ArrayList

I have the following code to set value by iteration.

for (int i=0; i<list.size(); i++){
    QuestionaireResult item = list.get(i);

    List<QuestionaireResultDetail> rsDetails = item.getQuestionaireResultDetails();
    List<QuestionaireResultDetail> filledList = fillList2(rs.getQuestionaireResultDetails(), rsDetails);
    item.setQuestionaireResultDetails(insertCommentObj3(insertCommentObj3(filledList, "C"), "B"));

    QuestionaireResultDetail qr2 = new QuestionaireResultDetail();
    qr2.setAnswerDesc(item.getRemark());        
    item.getQuestionaireResultDetails().add(qr2);

    list.set(i, item);
 }

however, I find I make change in the ith element, the 0th element also changes its value as the ith element, but I don't think I change that. Could someone give me advice about why that happen?

Thanks first.

Based on the description and the code given so far, I think there are only two possible (plausible) reasons:

  • The i th item and the 0 th item are the same
  • There are static variables involved

The first one could happen, for example, when the list is filled like this:

List<Item> list = new ArrayList<Item>();
Item item = new Item();
for (int i=0; i<3; i++)
{
    item.setSomeProperty(i);
    list.add(item);
}

In this case, you should make sure that a new item is created for each entry of the list:

List<Item> list = new ArrayList<Item>();
// Item item = new Item(); // Don't create a single instance here
for (int i=0; i<3; i++)
{
    Item item = new Item(); // Instead, always create a new instance
    item.setSomeProperty(i);
    list.add(item);
}

The second one could involve some static variable like in this example

class Item
{
    private static int someProperty;

    public void setSomeProperty(int i)
    {
        someProperty = i;
    }
}

In this case, you just have to make sure that the field is not static .

If neither of both is the case, then the code that you provided is not sufficient for finding the reason for the odd behavior.

Since your code is not complete, i am answering based on my Experience.

Your List<QuestionaireResultDetail> is an ArrayList of Objects of Type QuestionaireResultDetail .

Now the ArrayList stored the Objects. So when you add an object to the ArrayList its not actualy creating a copy Object, its actually making a reference to the Original Object. Hence any change in One object will be reflected to all the copies of that Object.

For Eg:

Object A= 12;
Object B=A;
B=10;

will make the value of A as 10. Because A and B points to the same location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM