Learn something new every day
More Info... by email
A dynamic array is a data structure used in computer programming that holds multiple computing objects as a single group, and can be resized at will to accommodate varying numbers of objects. The group is held in a single contiguous block of memory, so access to elements is efficient and fast. Dynamic arrays are also called vectors or lists, depending on the computer language in which they are used. Despite these names, any particular list or vector may not be a dynamic array, since lists and vectors may be implemented differently from arrays and from each other.
C++ contains a single dynamic array class called vector, which resides in a group of classes called the standard template library. The array that backs this class can be accessed by iterators or by indexes. Its ability to resize on demand is a great advantage, but it can lure programmers into a false sense of security because it isn't as robust as it seems to be. The dynamic array backing a vector can't ensure that access requests are valid. Like static arrays, dynamic arrays can have bounds checking and memory corruption problems if a program attempts to access memory that hasn't been allocated for them.
Java contains three distinct dynamic array classes: Vector, ArrayList, and CopyOnWriteArrayList. Elements in the array are only accessed by indexes, and attempting to access indexes outside of the array usually will not cause memory corruption issues. The Java Vector class is roughly equivalent to the C++ vector class, and is not synchronized to enable access by multiple threads. ArrayList and CopyOnWriteArrayList, by contrast, are both thread-safe. Of the three, CopyOnWriteArrayList is the most labor-intensive class, because it completely recreates the dynamic array every time a new value is written to the array.
Dynamic arrays are implemented in essentially the same way regardless of the computer language involved, but depending on a particular language there may be other capabilities built on top of it. Like static arrays, dynamic arrays do not restrict the type of object that can be stored inside them, as long as they are all the same type of object. A programmer never needs to access a dynamic array directly; it can always be done through a class that wraps the array for easy use. Proper use of these arrays can aid a programmer with data organization inside code, and also with creating understandable code that lends itself to easy maintenance.