1

I've got an ArrayList. The first index has a value of 10.

I want to add 10 to this index so that now it contains 20.

I tried:

ArrayListName.add(0, 10);

Which obviously overrides the field. How can I add in the 10 instead?

If this is a duplicate please refer me to the appropriate article

Many thanks.

2
  • Don't use ArrayListName as a variable name, java convention says a variable should start with lower case letter, not upper case (unless that's a final const, and then it should be all caps) Commented Feb 16, 2015 at 21:53
  • Amit I obviously would follow normal naming convention when using variables. I used the capitals for clarity but I see now it probably inhibits anyone else looking at this in the future. Commented Feb 16, 2015 at 22:00

1 Answer 1

1

What you are doing adds a new element to the array, at index zero, containing value 10. The "add()" method adds an element to the array, and does not perform mathematic addition.

To add a number to an existing element you'd do

ArrayListName.set(0, ArrayListName.get(0) + 10);

This replaces the element at index 0, with a new value that has the value of the original content of index 0, plus 10.

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

5 Comments

add inserts an element; it doesn't replace it.
Oops. I mistyped in confusion. I changed the code. It works now. If you could remove the downvote now that it works I'd be grateful. Thanks for pointing out my mistake!
Oh. Well then! Hopefully whoever did sees that I remedied my mistake. Thanks for pointing it out.
@JosephErickson Thank you. But you do know if it's the correct answer you're supposed to mark the check mark, right? If it's not correct, then thanks anyways!
I did know. It gives a cool down from the moment its asked for like 10 minutes ish.

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.