1

I have to replace an element in an ArrayList. Which is faster—using remove() and add() or getting the needed item index and using set(int, E)?

If you know some books about similiar themes, please give me some advice.

7
  • 2
    Arrays don't have these operations. In an arraylist set is highly likely to be the fastest since no resizing or node manipulation will be necessary other than referencing the new object. Commented Aug 26, 2016 at 14:11
  • 1
    set(int,E) is better I guess,since it replaces the element directly Commented Aug 26, 2016 at 14:11
  • Just wondering: you did some profiling, and you are sure that you really have to worry about such subtleties? Commented Aug 26, 2016 at 14:11
  • @GhostCat That's not a subtlety. Commented Aug 26, 2016 at 14:12
  • Just as a thought if you have to do that often a LinkedList would be faster to replace elements. However finding a specific element is slower Commented Aug 26, 2016 at 14:13

3 Answers 3

2

If this is the last item of ArrayList, almost no difference. In othe case - set(int, E) will be faster because no nee to copy part of array

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

Comments

2

It's all in the javadoc (emphasis mine):

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking).

To recap: set = O(1) whereas add/remove = O(n) ==> use set.

Comments

1

The remove(Object) will perform a linear search in your ArrayList and then remove the first occurrence of the specified object, which means that in the worst case you'll get an O(N) complexity.

If you already know the index to replace, for sure will be faster to call .set(index, object), but if you don't, there is no difference because in both cases you will have to perform a linear search getting O(N) complexity.

add(Object) always add the object at the end of the ArrayList, so it runs in O(1) complexity to add a single object in your ArrayList.

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.