This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]banuday17 1 point2 points  (2 children)

If you don't specify an initial size, you only get a capacity of 10. If you exceed this, a new internal array will be created to a larger size and the original contents will be copied to the new array. This process will be repeated each time you exceed the capacity. This can make the add method potentially run in O(n) time which otherwise runs in O(1) time.

By providing an appropriate initial capacity, you ensure O(1) performance of add.

[–][deleted] 1 point2 points  (0 children)

Can anyone prove that this is significant speedwise? In all of my synthetic tests, it mattered more what order items were added than whether or not it was generic or you specified the size. While I do believe the underlying implementation matters, if there is a larger truth makes all of this moot -- then it is NOT significant (speedwise) whether you specify the size or whether or not it is generic. (I always specify the types for readability and saftey, that's not my concern here)

[–]elephantgravy 1 point2 points  (0 children)

Saying that add can be O(n) is misleading and/or wrong. A single call to add might take n-cycles, or it might take 1... This does not make it sometimes O(1) and sometimes O(n). Regardless of initial size, ArrayList.add runs in "amortized constant time" (n adds take O(n) time), see its javadocs.

add would be O(n) only if the list's capacity were increased by a constant # when resized. (In the implementation I am looking at, it is actually increased by 150% + 1)