0

As the title says, I have two ArrayLists. Strangely, setting a value on one 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*

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@dylandrop No problem--you'd be surprised how often that trips people up, no matter how experienced.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.