2

A simple question: I store some values at an ArrayList at specific positions (indexes). These values are frequently updated by the code. My question is, in order to keep the ArrayList updated, it is sufficient to add the new value at the proper index (i.e. this action overwrites the older value stored there?) or do I have to remove first that value stored in that position of the ArrayList and then add the new value at this (now empty) position in the ArrayList?

1
  • 1
    As opposed to list.get(i).setXXX(...);? Commented Feb 10, 2014 at 1:49

1 Answer 1

8

The JavaDoc says...

set
public E set(int index, E element)

Replaces the element at the specified position in this list with the specified element.

Specified by: set in interface List

Overrides: set in class AbstractList

Parameters:
index - index of the element to replace
element - element to be stored at the specified position

Returns: the element previously at the specified position
Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

So, basically, you can simply override the value at a specific location...

You may also want to take a look at Collections

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

3 Comments

@PaulHicks Yeah, I was going for subtle... ;)
@PaulHicks Sorry, I got confused! I don't want to use Set, I have to use ArrayList. Does ArrayList presents same behavior as Set, i.e. the operation "add" overwrites the existing element stored at the specified index?
@Kotsos Yes. ArrayList is a descent of List, so it has set. This method is, infact, implemented by ArrayList directly, for it's required purposes.

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.