Java Array and ArrayList: Differences
Introduction
An array is a linear data structure that is used to store elements in a contiguous memory location. The ArrayList is a class in Java that is similar to a dynamic array and belongs to the collection framework. The ArrayList class works almost similar to the vector class in C++.
Ways to create an array in Java
1. Static array or Simple fixed-sized arrays.
2. Dynamically sized arrays
We can declare a static array and initialize it later or we can initialize an array at the time of declaration. Let us consider the following program that illustrates how we can declare a static and dynamic array:
Source Code
class HelloWorld { |
Output:
java -cp /tmp/s8IvllDeLH HelloWorld |
Output Description:
As you can see in the output, the first element of both the arrays have been displayed.
Creating an ArrayList
Java provides us the ArrayList class using which we can store elements just like a dynamic array. The ArrayList is a part of the collection framework in Java. We can access the elements of an ArrayList using the [] operator. The ArrayList class also provides methods to access elements.
We can declare an ArrayList in Java using the following syntax:
ArrayList<data_type> arraylist = new ArrayList<data_type>(); |
Source Code
import java.util.ArrayList; |
Output:
java -cp /tmp/s8IvllDeLH HelloWorld |
Output Description:
As you can see in the output, ArrayList elements have been displayed.
Differences Table
The differences between an ArrayList and an array are the following:
Array | ArrayList |
An array can be single-dimensional as well as multidimensional. | An ArrayList can be single-dimensional only. |
Operations on an array can be performed fast as compared to an ArrayList. | An ArrayList is slower than compared to Array. |
An array is static and thus has a fixed length. | An ArrayList is dynamic in nature and therefore can be increased or decreased accordingly. |
There are no other methods except the [] operator to add elements. | We have add() method to add elements in an ArrayList. |
The length keyword is used to retrieve the size of an array. | The size() method is used to retrieve the size of an ArrayList. |
Conclusion
In this tutorial, we discussed how we can create an array and ArrayList in Java. We also highlighted differences between array and ArrayList. We believe this tutorial has helped you to improve your Java knowledge.