Difference Between Array and Arraylist
In Java, arrays are fixed in size, meaning once they are created, you cannot change their size, whereas ArrayLists are dynamic, allowing elements to be added or removed after initialization. Arrays can store both primitive data types (like int, char) and objects, while ArrayLists can only store objects and use generics for type-safety.
Internally, an ArrayList uses an array to store its elements, but it automatically handles resizing operations when the stored data exceeds or reduces the array’s capacity.
What is Array?
An array is a collection of the same type of elements that are grouped together and referred to by a common name is called an array. These elements are homogeneous in nature meaning they should be of the same datatype for e.g. String,int, float etc.
We generally use arrays when we are dealing with thousands of variables of the same data type. For example, suppose we want to store the marks of 1000 thousand Maths Subjects. We have two choices, either we create thousands of variables manually or create a single group of these variables called arrays.
What should you do? Yes, you will definitely use arrays because the management of the data is much easier in the array than creating thousands of variables. We can also perform searching operations on the elements of an array. This is one of the properties of the array.
Let’s discuss all major properties of the array. In array creation, there are basically three steps: declaration, instantiation, and initializing the array. Let’s discuss these steps one by one thoroughly
- Declaration of an array: The declaration of the array follows the same logic and rules as declaring variables in the java language like the type of the data and the valid name of the array. We can declare an array of all basic data types such as int, float, boolean, etc.
Syntax: \<Datatype> \<variablename> \ or \<Datatype> \ \<variable name>
- Datatype: The type of data for which we want to declare an array. For example, Integer or int both are used to store number values.
The syntax of declaring an array is first we mention the type of data of which we want to declare an array and the valid name of the variable.
What is ArrayList?
ArrayList is a resizable array or we can say it is a dynamic array that is a part of the collection framework in java that is present in the util package. The main advantage of ArrayList over an array is the size of the ArrayList changes during the run time of the program but in the case of an array, the size of the array remains constant once instantiation is done in the java program. Even the deletion of the elements in the ArrayList is much easier than the array in the array.
When we delete the middle element in the array we have to rearrange all remaining elements but ArrayList provides us with various inbuilt functions that help to perform many operations easier. Let’s discuss the characteristics of the ArrayList.
The Declaring of the ArrayList is similar to the array’s Declaration. Similar to arrays, it is required to specify the data type of elements in an ArrayList and also while Instantiation of the ArrayList we need not to mention the size of the ArrayList like in the arrays we have to mention the size of the arrays during the instantiation process.
This is the structure of ArrayList in java. We have mentioned the Initial Capacity of the ArrayList i.e 8 and we are inserting elements in the elements in a continuous manner.
- Typename: In the type name we specify what kind of data value ArrayList will store. For example String, Integer, etc In the case ArrayList. In the declaration of Arraylist, we cannot use int, float, double, etc as a type name in the ArrayList because ArrayList implements a collection interface that accepts only object data types only.
Let’s understand this using an example.
The first declaring of the ArrayList is the valid declaring because Integer is the object data type in the second case int is not an object data type that’s why this is an invalid declaring of the ArrayList.
Key Difference Between Array and ArrayList
In the context of Java, “Array vs ArrayList” brings to light several differences. Firstly, arrays are of fixed size, determined at the time of declaration, while ArrayLists are dynamically resizable. Secondly, arrays can hold both primitive data types and objects, whereas ArrayLists are limited to object storage, utilizing autoboxing for primitives. Thirdly, ArrayLists come with built-in methods for various operations like adding or removing elements, whereas arrays do not offer such flexibility. Lastly, an ArrayList internally uses an array for data storage, but it automatically manages resizing when necessary.
In Java, the distinction between “array vs ArrayList” stems from arrays being fixed-size with support for primitives and ArrayLists being dynamically resizable but restricted to object storage.
Difference Between Array and ArrayList
|Resizable||The array is not resizable. At instantiation, you must provide its maximum size. Overfilling leads to an exception.||ArrayList is dynamically resizable. It grows as required, even beyond its initial capacity, offering flexibility in the number of elements it can store.|
|Performance||Arrays generally offer better performance than ArrayLists because they are of fixed size and don’t require internal operations to store elements.||ArrayList can be slower, especially when increasing in size. This is because, when its capacity is exceeded, a new array is created internally, and existing elements are copied over, reducing its performance.|
|Size Method||Use Array.length to determine the length of an Array. For example: int arr=new int; System.out.print(arr.length); will print 4.||The size() method determines the length of an ArrayList. Example: ArrayList<Integer> A = new ArrayList<Integer>(); A.add(1); A.add(2); System.out.println(A.size()); will print 2.|
|Dimension||Arrays support multiple dimensions (e.g., 2D, 3D arrays). For instance, int arr=new int; creates a 2D array with 4 rows and 3 columns.||ArrayList supports only single dimensions, and isn’t suitable for tasks like matrix creation.|
|Data Type||Arrays support both primitive types (like int, char) and object types.||ArrayList supports only object types due to its use of generics. For instance, instead of int, you’d use Integer.|
|Null Values||Arrays can hold null values. However, for primitive arrays, there’s no null (e.g., an int array defaults to 0 for each position unless otherwise assigned).||ArrayLists can contain and identify null elements.|
|Built-in Methods||Arrays offer limited built-in functionalities.||ArrayList offers a variety of built-in methods from the Java Collections Framework, like add(), remove(), and clear(), providing more functionality and ease-of-use.|
|Synchronization||Arrays aren’t synchronized, so they’re not inherently thread-safe.||ArrayList is also not synchronized by default. However, synchronization can be added externally using Collections.synchronizedList().|
Instantiation of an Array
In the declaration of an array, we simply create a reference of the array, we cannot insert any kind of value in the array without allocating the memory space to the array. We know very well that the Java language follows the OOP concept and in Object-Oriented Programming, the allocation of the memory is done with the help of the new() keyword. So the Instantiation of an array is as follows:
Syntax of Instantiation of the array: \<Datatype>\<variablename>=new \<data type>\[sizeof array]
The data type denotes the type of array which we want to create
Below is the example of the array instantiation
In the above initialization, 5 blocks of 4 bytes are allocated in the memory because each block has its own unique address as we can see clearly in the below picture. The array instantiation looks similar.
Initializing the Arrays
The array initializing the array means initializing the values in the array with the help of the indexing procedure. The indexing in the array starts with 0. Now think about why the indexing of the array starts with 0, not 1? The simplest answer is indexing is nothing but it is the distance of the starting of the array that’s why the indexing starts from 0, not 1.
Please look at the below diagram for a better understanding-
In the above diagram, the proper steps of the array creation are described how the array is managed in the memory and how initializing is done in the block of the array.
Now think about what will happen if we want to insert an extra element when the array contains maximum elements to its size.
Let’s understand this situation with the help of an example.
In the above code, the array can contain only three elements but when we try to insert an extra element in the array an exception is thrown by the main method, the exception is ArrayIndexOutofBoundException.
Scaler world will not print due to this exception in the programming. This is the main disadvantage of the array, we cannot insert extra elements in the array than the specified maximum elements in the array. Now how to deal with this problem one of the best ways to handle this problem is using the ArrayList in the place of the arrays in the java program. Let’s discuss the functionality of the ArrayList in Java.
Accessing Element in Arrays
We can access the elements in the arrays with the help of the indexing that starts from 0 to n-1. Where n is the length of the array. The indexing should be in the range [0,n-1]. Out of the range indexing causes a compilation error.
In the above example, we are accessing the element which is stored in the first position of the array arr.
The above snippet prints the first element of the array.
Instantiation of an ArrayList
In the declaration of an Arraylist, we simply create a reference of the ArrayList, we cannot insert any kind of value in the array without allocating the memory space to the array. We know very well that the Java language follows the OOP concept and in Object-Oriented Programming, the allocation of the memory is done with the help of the new() keyword. So the Instantiation of an Arraylist is as follows:
Syntax of Instantiation of the Arraylist:
\<Arraylist>\<typename>\<variable name>=new Arraylist(InitialCapacity);
- Typename: In the type name we specify what kind of data value Arraylist will store. For example String, Integer, etc In the case of ArrayList. In the declaration of Arraylist, we cannot use int, float, double, etc as a type name in the ArrayList because ArrayList implements a collection interface that accepts only object data types only.
- Variable name: This is the proper name for the ArrayList
- Initial Capacity: This is the optional parameter in the ArrayList instantiation that is used to specify the initial size of the ArrayList.
Now think about what will happen if we add an extra element than the capacity of the ArrayList.
Let’s understand this using an example
In the above program, the ArrayList is instantiated with the size 3 but when the extra element is added to the ArrayList that increases the initial capacity of the ArrayList. The ArrayList internally resizes its capacity by creating a new array of size greater than the previous capacity of the ArrayList and uses this array as a reference for storing the new elements in the ArrayList. That’s why at last 4 will be printed as the new capacity of the ArrayList.
Inserting Elements in the ArrayList
There are two ways to insert elements in the ArrayList at the particular index of the ArrayList or the end of the ArrayList.
Syntax: ArrayList.add(Index, Element)
- Index: The position at which we want to add the specific element in the ArrayList.
- Element: The element which we want to add in the ArrayList.
This is the method used to insert elements in the ArrayList at the particular index. Let’s discuss the insertion procedure in the ArrayList using an example.
First, there are two elements in the ArrayList. The first printing line will print [1,2] after this at index 1 12 is inserted in the middle of the ArrayList. So the final ArrayList will be [1,12,2 ].If we want to insert an element at the index greater than the length of the ArrayList the java compiler will show an error because this method is used for updating the elements in the range of the length of the ArrayList.
Syntax: ArrayList.add( element)
Element: The element which we want to add in the ArrayList.
This is the method used to insert an element in the ArrayList at the end of the ArrayList.
Let’s discuss the insertion procedure in the ArrayList using an example.
First, there are two elements in the ArrayList. The first line will print [1,2] after this at the end element 12 is inserted at the end of the ArrayList. So the final ArrayList will be [1,2,12 ].The insertion of elements in the ArrayList in a continuous manner hence the order of elements in the ArrayList during insertion is maintained.
Accessing Elements in the Arraylist
We can access the elements in the ArrayList using indexing similar to the accessing elements in the arrays but in the case of the get() function is used for accessing the elements of the ArrayList.
- Index: The position at which we want to access the specific element in the ArrayList Note: The range of indexing should be in the range [0,Arraylist.size()-1] of the ArrayList
In the above snippet, we are accessing the first element using 0th indexing and in the second case, we are mentioning wrong index values that cause compilation errors in the program.
Deleting element in ArrayList
Index: index of the element which we want to remove from the arraylist. The range of indexes lies in the range [0,ArrayList.size()-1].
Note: The range of indexing should be in the range [0,Arraylist.size()-1] of the ArrayList
In the above snippet, we are removing the element that is present at index 1.
- The primary difference between array and ArrayList in Java is that arrays are of fixed size, whereas ArrayLists are dynamic and can grow or shrink as needed.
- Another significant difference between array and ArrayList is that while arrays can hold both primitives and objects, ArrayLists can only store object references, relying on autoboxing for primitives.