Difference between Array and ArrayList

  • Resizable
    • Array is static in size that is fixed length data structure, One can not change the length after creating the Array object.
    • ArrayList is dynamic in size. Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. Its capacity grows automatically.
  • Primitives
    • Array can contain both primitive data types (e.g. int, float, double) as well as objects.
    • ArrayList can not contains primitive data types it can only contains objects.
  • Adding elements
    • In array we insert elements using the assignment(=) operator.
    • We can insert elements into the ArrayList using the add() method
  • Length
    • Each array object has the length variable which returns the length of the array.
    • Length of the ArrayList is provided by the size() method.

ArrayArrayList

// Array

int[] integerArray = new int[3];

integerArray[0] = 1;

integerArray[1] = 2;

integerArray[2] = 3;

for (int i : integerArray) System.out.println(i);

for (int j=0; j<integerArray.length; j++) System.out.println(integerArray[ j ]);

int k = 0;

while (k < integerArray.length) System.out.println(integerArray[k++]);

 

// ArrayList

ArrayList<Integer> integerList = new ArrayList<Integer>();

integerList.add(1); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

integerList.add(2); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

integerList.add(3); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

for (int m : integerList) System.out.println(m);

for (int n=0; n<integerList.size(); n++) System.out.println(integerList.get(n));

Iterator<Integer> itr = integerList.iterator();

while (itr.hasNext()) System.out.println(itr.next());