views:

382

answers:

5

When to use ArrayList and when to use Arrays?

A: 

ArrayLists are good for when you don't really know the size of what you need at instantiation. They have built in Add/Remove methods and a few other methods to help manage the objects more easily. Arrays are a little more compact, but they are clunky to work with in a dynamic fashion by comparison. If you have a grouping of classes or other objects, you may want to look at Generics with the List class.

Joel Etherton
+1  A: 

For java, at least, an ArrayList can grow and shrink dynamically at runtime, whereas an Array cannot.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

from http://java.sun.com/javase/7/docs/api/java/util/ArrayList.html

davek
A: 

ArrayList is provided in most programming languages. It is a wrapper over an array, and thus has lot of easy-to-use functionalities, e.g. insert, delete, auto grow. However, you should remember these are implemented using regular arrays, and you can implement them yourself. For some reason, you may want to write high-performance code and you are not sure about the implementation in ArrayList, you can pick Array.

Bryan
A: 

Generally speaking it is almost always preferable to use ArrayList over plain old Array. Array's main purpose is to provide a base class for other data structures to inherit from. ArrayList is a much more robust data structure with very useful methods such as Insert, Remove, RemoveAt, Contains, and Add, all methods you would have to deal without if using a plain old Array.

Also ArrayLists are dynamically managed for you by your run time system. If you attempt to add one item to many to an Array you will get an exception. An ArrayList will simply grow in size to accomodate the new item.

Long story short, if you are creating a new data structure and would like something to build on top of, use Array. Otherwise, as far as data management in concerned, you're probably looking to use an ArrayList. Is some cases, I would even build off of the ArrayList over the Array...

Steve H.
A: