What is Difference Between Array and ArrayList in Java - onlyxcodes

Saturday, 6 May 2023

What is Difference Between Array and ArrayList in Java

Managing data effectively is one of a programmer's primary goals.


Two significant and often-used data structures in Java are array and ArrayList.


The array data structure, which has been around for a very long time, is one of the most used ones for storing data. The array's simple implementation is the reason it is used so frequently.


The Java collection framework also has an additional feature called ArrayList.


A fixed-length data structure is an array. Once it has been constructed, its size cannot be altered. The Java programming language introduces the ArrayList to address this array flaw. 


Let's go into more detail about the Java differences between Array and ArrayList.


difference between array and arraylist in ava

What is an Array in Java?

A fixed-size collection of elements with the same data type is referred to as an array in Java. An array's size cannot be altered once it has been constructed. The index number of an array element, which starts at 0, can be used to access it.


An illustration of how to declare an array of numbers in Java is given here:


Syntax:


datatype array_name = new dataype[Size_of_Array];

Example:


int arr = new int[3];

arr[0] = 10; 
arr[1] = 20; 
arr[2] = 30;

What is ArrayList in Java?

An ArrayList, on the other hand, is a dynamic collection of elements that can change in size while the program is running. 


Any data type can be stored in an ArrayList, which also offers methods for adding, removing, and accessing elements. 


An ArrayList, in contrast to an array, does not need to have a fixed size and can be resized as necessary.


Here is an illustration of how to declare a string ArrayList in Java:


In this example, we first declare a country-named empty ArrayList of strings. The add() method is then used to add three strings to the ArrayList.


Syntax:


ArrayList <Wrapper Class> object_name=new ArrayList<Wrapper Class>();

Example:


ArrayList<String> country = new ArrayList<String>();
country.add("australia");
country.add("canada");
country.add("germany");

The Differences Between Array and ArrayList are:

Size:


When an array is created, its size is fixed and cannot be modified. 


In contrast, depending on the number of elements added or removed, an ArrayList can expand or contract dynamically.


import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList 
{

    public static void main(String[] args) 
	{
        // Initializing an array of integers
		// Fixed size and can’t add more than 3 values.
        int[] arr = new int[3];
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        

        // Initializing an ArrayList of integers
		// Variable size        
		// Can add more elements.  
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
		list.add(4);

        // Printing the array elements 
		
        System.out.println(Arrays.toString(arr));	
		
		System.out.println("------------------------");

	    // Printing the ArrayList elements
		
        System.out.println(list);
    }
}

Output:


[1, 2, 3]
------------------------
[1, 2, 3, 4]

Type: 


Arrays have a fixed size but can store objects and primitive data types (int, float, and double). 


ArrayLists, however, can only hold objects. It has the capacity to dynamically expand and deal.


import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList 
{

    public static void main(String[] args) 
	{
        
        int[] arr = new int[3];
		
		ArrayVsArrayList[] arr1 = new ArrayVsArrayList[3];
        

        ArrayList<Integer> list1 = new ArrayList<Integer>();
		ArrayList<String> list2 = new ArrayList<>();
        ArrayList<Object> list3 = new ArrayList<>();
		
        System.out.println("Compile and Run Done Successfully");	
		
    }
}

Output:


Compile and Run Done Successfully

Initialization:


Arrays may have a set of beginning values. 


ArrayLists, on the other hand, can have values added to them after they have been initialized.


Length:


The length variable, which is present in every array object, returns the array's length. 


While the size() method returns the ArrayList's length.


For example,


The array object length variable is used in this statement.


Integer arrayobject [ ] = new Integer[5];
arraylength= arrayobject.length;

The ArrayList object size method is used in this statement.


ArrayList arraylistobject = new ArrayList();
arraylistobject.add(15); 
arraylistobject.size( ); 

Adding Value:


We use the assignment operator to add values to the array.


The add() method can be used to add values to the ArrayList object.


For example,


The following statement adds a new object to the array object that has been supplied. 


One of the most significant variations between an array and an ArrayList is this. 


Integer addarrayobject[ ] = new Integer[8];
addarrayobject[0]= new Integer(3);  

Performance:


Because members are stored in adjacent memory regions, arrays perform random access operations more quickly than ArrayLists.


Since underlying arrays are used by ArrayLists to store elements, updating the array size when it is exceeded can take longer.


Due to the formation of a new array and subsequent copying of the contents of the existing array to the new array, every resize() operation on an ArrayList may result in performance degradation. As a result, this action causes ArrayList to perform slowly.


Multi-Dimensional:


Single or multiple dimensions can exist in an array. However, an ArrayList can only have one dimension.  


An illustration of a two-dimensional array is shown below:


The declaration for a string array with 2 rows and 2 columns named "str" is as follows.


In this illustration, four separate strings are each kept in a string array with the following values: France Blue, Ireland Green.


import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList 
{

    public static void main(String[] args) 
	{
        String[][] str = new String[2][2];
		
		str[0][0]="France";
		str[0][1]="Blue";
		str[1][0]="Ireland";
		str[1][1]="Green";

        // Loop through all rows
        for (String[] row : str)
		{
			System.out.println(Arrays.toString(row));
		}	
    }
}

Output:


[France, Blue]
[Ireland, Green]

Methods:


ArrayLists offer a variety of methods to manipulate the data they contain, whereas Arrays have a limited number of methods.


Flexibility:


The main characteristic that distinguishes the array from the ArrayList in Java is flexibility. 


In Java, ArrayList is more adaptable than Arrays. This is due to the dynamic nature of ArrayList. ArrayLists can grow automatically when more elements are added than they can hold, but arrays cannot. 


In addition, we can remove elements from an ArrayList, which is not feasible with arrays. After adding elements to an array, we cannot take those elements away.


Understand the Differences Between Array and ArrayList with Java Programs

Here are some Java examples of programs that show how an array and an ArrayList vary from one another.


How to get all elements from Array and ArrayList in Java?

With the same items, this program generates an ArrayList of integers and an array of integers. The elements of the array and the ArrayList are then printed out.


import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList 
{

    public static void main(String[] args) 
	{
        // Initializing an array of integers
        int[] arr = new int[5];
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        arr[3] = 4;
        arr[4] = 5;

        // Initializing an ArrayList of integers
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        // Printing the elements of the array
		
        System.out.print("Array elements: ");
		
        for (int i = 0; i < arr.length; i++) 
		{
            System.out.print(arr[i] + " ");
        }
		
        System.out.println();

		
        // Printing the elements of the ArrayList
		
        System.out.print("ArrayList elements: ");
		
        for (int i = 0; i < list.size(); i++) 
		{
            System.out.print(list.get(i) + " ");
        }
		
        System.out.println();

    }
}

Output:


Array elements: 1 2 3 4 5
ArrayList elements: 1 2 3 4 5

Change Specific Index Value of Array and ArrayList Java Example

In this Java program, the third element of the array and the ArrayList are both changed to have the number 7. The elements of the array and the ArrayList are then printed once more.


import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList 
{

    public static void main(String[] args) 
	{
        // Initializing an array of integers
        int[] arr = new int[5];
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        arr[3] = 4;
        arr[4] = 5;

        // Initializing an ArrayList of integers
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        // Printing the elements of the array
		
        System.out.print("Array elements: ");
		
        for (int i = 0; i < arr.length; i++) 
		{
            System.out.print(arr[i] + " ");
        }
		
        System.out.println();
		

        // Printing the elements of the ArrayList
		
        System.out.print("ArrayList elements: ");
		
        for (int i = 0; i < list.size(); i++) 
		{
            System.out.print(list.get(i) + " ");
        }
		
        System.out.println();

        
		// Changing an element in the array
        arr[2] = 7;

        
		// Changing an element in the ArrayList
        list.set(2, 7);
		
		
		System.out.println("--------------------------");
		

        // Printing the elements of the array after the change
		
        System.out.print("Array elements after change: ");
		
        for (int i = 0; i < arr.length; i++) 
		{
            System.out.print(arr[i] + " ");
        }
		
        System.out.println();
		

        // Printing the elements of the ArrayList after the change
		
        System.out.print("ArrayList elements after change: ");
		
        for (int i = 0; i < list.size(); i++) 
		{
            System.out.print(list.get(i) + " ");
        }
		
        System.out.println();
    }
}

Output:


Array elements: 1 2 3 4 5
ArrayList elements: 1 2 3 4 5
--------------------------
Array elements after change: 1 2 7 4 5
ArrayList elements after change: 1 2 7 4 5

How do you Access a Single Element in an Array and ArrayList in Java?

The single element of the array and the ArrayList is obtained in this Java program, and both elements are then printed out.


In this program, Arrays access items using square brackets (e.g. arr[2]), but ArrayLists access elements using the get() function (e.g. list.get(2)).


import java.util.ArrayList;

public class ArrayVsArrayList 
{

    public static void main(String[] args) 
	{
        // Initializing an array of integers
        int[] arr = new int[5];
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        arr[3] = 4;
        arr[4] = 5;

        // Initializing an ArrayList of integers
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        // Printing the single element of the array
		
        System.out.println("Print Single Array Element: ");
		
        System.out.println(arr[2]);
        
		
        System.out.println("------------------------");
		

        // Printing the single elements of the ArrayList
		
        System.out.println("Print Single ArrayList Element: ");
		
        System.out.println(list.get(2));
        
    }
}

Output:


Print Single Array Element:
3
------------------------
Print Single ArrayList Element:
3

What are Some Differences Between an Array and an ArrayList in Java?

The initialization and accessing of its elements are the two main areas where an array and an ArrayList diverge. 


While ArrayLists can expand or shrink dynamically as elements are added or removed, Arrays are initialized with a fixed size. 


ArrayLists offer more flexibility and convenience, but arrays are also quicker and more memory-efficient.


Java Array and ArrayList Similarities

The data structures Array and ArrayList are both used to hold data of the same type.


Both Array and ArrayList can store null values.


They can include duplicate values, but the data type must be the same.


The elements' original order is not maintained.


Learn More:

Can you print a string array in Java

Can you Remove an Element from an Array in Java

Can we compare 2 arrays in Java?

How to Create a 2D Array Dynamically in Java

What is Array in Java with Example

What is the Long Array in Java with Example

How to Add Value to an Array in Java

No comments:

Post a Comment

Post Bottom Ad