Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .add(i, E) big O(n) in Java ArrayList?

I'm wondering why exactly .add(i, E) is O(n) when .get(i) is O(1)? Is it because potentially n elements must be shifted over to the right after the insertion?

like image 590
Adam Thompson Avatar asked Sep 05 '26 23:09

Adam Thompson


1 Answers

remember Big O notation shows the Order of magnitude of the problem not its best case solution... so yes shifting the other elements in the ArrayList (backed by an Array as Siddhartha mentions) is what causes it to be O(n).

like image 96
Paul Henry Avatar answered Sep 07 '26 11:09

Paul Henry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!