开发者

ArrayLists, setting a value on one ArrayList changes a value on another

开发者 https://www.devze.com 2023-04-13 04:47 出处:网络
As the title says, I have two ArrayLists. Strangely, setting a value on o开发者_JAVA百科ne arraylist changes that of another.

As the title says, I have two ArrayLists. Strangely, setting a value on o开发者_JAVA百科ne arraylist changes that of another.

Some information: these are ArrayLists of type Entry, each of which holds an amount and a value (which is what you see in the parentheses). I'm trying to turn this array: [(5,2)(2,5)(3,2)]

into these [(1,2)] and [(4,2)(2,5)(3,2)]. i == 1 in this case, and remainingAmt == 1.

ArrayList<Entry> firstHalf = new ArrayList<Entry>();
    ArrayList<Entry> secondHalf = new ArrayList<Entry>();

    for(int j = 0; j<=i;j++){
        firstHalf.add(rleAL.get(j));
    }
    for(int k = i; k<rleAL.size(); k++){
        secondHalf.add(rleAL.get(k));
    }
    System.out.println(firstHalf);//gives (5,2)
    firstHalf.get(i).setAmount(remainingAmt);
    System.out.println(firstHalf);//gives (1,2) *CORRECT*
    secondHalf.get(0).setAmount(rleAL.get(i).getAmount() - remainingAmt);
    System.out.println(firstHalf);//gives (0,2) *WRONG*


Nothing unusual there--if the underlying objects are shared between lists, a change in one object will be reflected in the other. If you need the lists to be independent, you need to use different objects in each list by either creating new objects from scratch, or copying the initial object to a new object in list #2.


The only problem here is in your title. You haven't 'set a value on one ArrayList' at all. You've set a value in an object which is a member of both ArrayLists, so of course it shows up in both.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号