Thursday, September 18, 2014

[Java] Difference between Array vs ArrayList in Java (campare with table)


The points are got from the reference links and shown with a table. So that it looks clearer than reading a block of article. If there is something missed, I would update this table later.

Array
ArrayList
Static data structure (Fixed length data structure)
Once created you can not change size of Array. number of items in array is static, good for a well-defined number of data items
Dynamic data structure (is a variable length Collection class)
It means the data structure us allowed to grow and shrink as the demand for storge arises. Once created you can change size of Array.
Java Default Data Type
While Array is part of core Java programming. and has special syntax and semantics support in Java,
Need import library
While ArrayList is part of Collection framework along with other popular classes e.g. Vector, Hashtable, HashMap or LinkedList. It need import the lbrary:
import java.util.ArrayList;
Can store either primitive or objects
Can store objects only
use .length() to count Array size

use .size() to count ArrayList size
Can not store primitives
Array can contain both primitives and Objects in Java.Though Autoboxing of Java 5 may give you an impression of storing primitives in ArrayList, it actually automatically converts primitives to Object
Can not store primitives
Since ArrayList can only contain Objects.
Can't create instance of ArrayList without specifying size

Can create instance of ArrayList without specifying size
Java will create Array List with default size but its mandatory to provide size of Array while creating either directly or indirectly by initializing Array while creating it. By the way you can also initialize ArrayList while creating it.


If you know the numbers of items to store, using an array.
If you can’t sure how many items and please use ArrayList so that can grow and shrink as the demand for storage.

Reference:

No comments :

Post a Comment