Monday, November 5, 2012

Java: Arrays vs ArrayList

Difference between ArrayList and 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.

No comments :

Post a Comment