1

Say there is a list of numbers. What is the difference between adding add(int index, Object x)

and setting an object to the list set(int index, Object x). Don't they essentially do the same thing? Aren't both functions just adding the Object x to the specified index?

3 Answers 3

2

set replaces, add pushes everything after index back an index.

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

1 Comment

Simple and clear, so the size of the array increases when add is used, and set keeps the size the same. I should have known, thanks again.
1

Set override your value at index position, add extends your values in array(old values remains) and put new value into index position.

Comments

1

From the documentation http://docs.oracle.com/javase/7/docs/api/java/util/List.html

add(int index, E element) Inserts the specified element at the specified position in this list (optional operation).

set(int index, E element) Replaces the element at the specified position in this list with the specified element (optional operation).

So no. They don't do the same thing. add adds. set replaces an existing element.

If there is no element a the index, set will return an error:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

You could, therefore, try them both:

try
{
   list.set(index, obj);
}
catch(IndexOutOfBoundsException ex)
{
   list.add(index, obj);
}

Try to set, and if it returns that specific error, add instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.