Array&Array List Programs
Array&Array List Programs
Array&Array List Programs
Note: As a side note, ArrayList in Java can be seen as similar to vector in C++.
Now let us illustrate examples with the help of differences between Array and
ArrayList
Example:
// Main class
class GFG {
// ArrayList
// Creating an arrayList with initial capacity
// say bi it 2
ArrayList<Integer> arrL = new ArrayList<Integer>(2);
Example:
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Normal Array
// Need to specify the size for array
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
// ArrayList
// Need not to specify size
Note: When we do arraylist.add(1) than it converts the primitive int data type into
an Integer object which is as illustrated in below example
Example:
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
// allowed
int[] array = new int[3];
// Allowed
ArrayList<Integer> arrL1 = new ArrayList<>();
ArrayList<String> arrL2 = new ArrayList<>();
ArrayList<Object> arrL3 = new ArrayList<>();
On the other hand, in the array, it depends whether the array is of primitive type
or object type. In the case of primitive types, actual values are contiguous
locations, but in the case of objects, allocation is similar to ArrayList. Java
ArrayList supports many additional operations like indexOf(), remove(), etc. These
functions are not supported by Arrays.
We have implemented and seen the differences between them as perceived from
outputs. Now let us wrap up the article by plotting conclusive differences in a
tabular format a shown below as follows: