Wednesday, August 19, 2009

Difference ArrayList and Array in Java

Welcome back again on Java Code Online. Today I would be discussing the main difference between an ArrayList and an Array in Java.

In Java an Array is always of fixed size. The size has to be defined at the initializing time of the array. The number of the rows is a must for any array, though the number of columns may be specified later. By using Array, there is comparatively less flexibility, as the size need to be known before hand. And if you initialize an array that is too long, then it results in wastage of precious memory of the heap. The Garbage Collector then has a tough time maintaining the memory for other resources.

On the other hand, the ArrayList is dynamic in nature. It provides for automatic resizing of the List. Moreover you need not specify the size at the beginning of the initialization part. The ArrayList is therefore much more widely used as compared to an Array in Java. ArrayList is and extension of the List Interface. So it is a part of the Collections framework.

Talking about the drawbacks of ArrayList, then there is probably only one, and that is typecasting. When an Object is added to an ArrayList it goes inside as an Object, and so when it is retrieved back, then it needs to be typecast back into the original Object.

The Arrays have a positive point in this regard, that is an array is always of a particular type that is an array of ints, or an array of Strings, etc. So when data is retrieved back from an Array, then no typecasting is required.

More or less the advantages of an ArrayList makes it one of the most versatile and important tool in the Java coding, and arrays are left far behind in the race of fame.

Keep buzzing Java Code Online for more info on Java.


  1. Your article related to array list and array have really helped me to understand what is actually arraylist and whats its use.Since long time i was trying but couldn't but your article helped was really nice

  2. Alok Patoria said

    It's fine but hidden someconcepts of Array List
    are not given here like its memory Allocation.
    It has its own paremeters for memory allocation which is also a major draw back of Array List.
    for eg
    for 0 elements it holds 0 capacity,for 1 it holds-4 capacity, for 2-4 its same,for 5-8 it holds-8 capacity,for 9 it holds -16 capacity.


Note: Only a member of this blog may post a comment.