views:

262

answers:

3

I was wondering if anyone knows the growth policy of ArrayList in Java 1.6? The java doc says

The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

But I just wonder the details because I know the size I'm targeting to start but I want to make sure I'm making the initial size big enough to not cause an instant resize. I know with HashMap you can set a load factor is there something similar happening in the back ground? Or is it always growing when space is out?

A: 

You can read the source for yourself. Every copy of the Sun JDK comes with a src.zip that contains the source.

bmargulies
+2  A: 

This is what I see when I look at the source of ensureCapacity:


    int newCapacity = (oldCapacity * 3)/2 + 1;
CPerkins
I see that's how much it grows by and it does the ensureCapacity when called but I was more wondering when it will resize.
Jeff Beck
Ah, ok. Well, x4u has answered that quite well.
CPerkins
+2  A: 

ArrayList doesn't need a loadFactor as it always grows when it is 100% filled, so you can create it with exactly the size you know in advance and it won't grow if you fill that many elements in later. Hashtables on the other hand become ever more inefficient the more they are filled, and thus you can ajust the tradoff between performance and wasted space with the loadFactor, but this isn't the case for growable Arrays like ArrayList.

x4u
Thanks that is exactly what I was looking for if in Java it grows when 100% filled or the ensureCapacity is called.
Jeff Beck