Java ArrayList

by Geethalakshmi 2011-03-17 10:07:33

Java ArrayList


java.util.ArrayList allows for expandable arrays, and is basically the same as the older the Collections Vector class. An ArrayList has these characteristics:

* An ArrayList automatically expands as data is added.
* Access to any element of an ArrayList is O(1). Insertions and deletions are O(N).
* An ArrayList has methods for inserting, deleting, and searching.
* An ArrayList can be traversed using a foreach loop, iterators, or indexes.

Use ArrayList when there will be a large variation in the amount of data that you would put into an array. Arrays should be used only when there is a constant amount of data. For example, storing information about the days of the week should use an array because the number of days in a week is constant. Use an array list for your email contact list because there is no upper bound on the number of contacts.

A possible disadvantage of ArrayList is that it holds only object types and not primitive types (eg, int). To use a primitive type in an ArrayList, put it inside an object or use of the wrapper classes (eg, Integer, Double, Character, ...). The wrapper classes are immutable, so if you use, eg, Integer, you will not be able to change the integer value. In this case it may be more useful to define your own mutable class.

ArrayLists are implemented with an underlying array, and when that array is full and an additional element is added, a new, larger, array is allocated and the elements are copied from the old to the new. Because it takes time to create a bigger array and copy the elements from the old array to the new array, it is a slightly faster to create an ArrayList with a size that it will commonly be when full.

Tagged in:

1872
like
0
dislike
0
mail
flag

You must LOGIN to add comments