In this tutorial, you will learn to work with Array and ArrayList in Java. You will learn to declare, initialize, and differences between Array Vs ArrayList with the help of examples.

 

Introduction

Both Array and ArrayList are two important used structures in Java and frequently used in Java programs. Even though ArrayList is internally backed by an array, knowing the difference between  Array Vs ArrayList in Java is critical for becoming a good Java developer.

 

Array

An array class is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index, and so on.

 

ArrayList

The ArrayList class is a resizable array, which can be found in the java.util package. The difference between a built-in array and an ArrayList in Java is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

 

Array Vs ArrayList In Java

  Array ArrayList
Resizable An 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. As elements are added to an ArrayList its capacity grows automatically.
Iterate We can use for loop or for each loop to iterate through the array We can use an iterator to iterate through ArrayList. The iterators returned by the ArrayList class’s iterator and list iterator method are fail-fast.
 Data Type An array can contain both primitive data types as well as objects of a class depending on the definition of the array. ArrayList only supports object entries, not the primitive data types.
Length  Length of the ArrayList is provided by the size() Each array object has the length variable which returns the length of the array.
Adding elements In array, we insert elements using the assignment operator. We can insert elements into the ArrayList object using the add() method.
Dimensional An array can be multidimensional. ArrayList is always single-dimensional

 

Thanks in advance for sharing… Sharing is caring…

Leave a Comment

1 Comment