Array vs ArrayList in Java Learn with Examples

Free Java courses with 37 real-time projects - Learn Java

One of the main objectives of a programmer is to handle data efficiently. There are numerous data structures that help programmers perform data handling. Array is one of the most used data structures to store data, it has been around for a very long time. The reason why array is used so often is due to its simple implementation. This helps newcomers understand data structure at an ease. There is another provision in the java collection framework, known as ArrayList. In this article, we will take a look at all the similarities and dissimilarities of Array vs ArrayList in java.

What is an Array in Java?

An array is a simple data structure with a contiguous memory location, in which data are stored with the same name but different index numbers. The data stored in an array must be of the same type. The size of an array is fixed after declaration.

Syntax:

datatype array_name = new dataype[Size_of_Array];

Example:

int Arr = new int[100];

What is an ArrayList in Java?

Unlike Array, ArrayList is a dynamic data structure that is part of the java collection framework. It also contains elements of the same type. Here we do not need to specify the size of the list.

Syntax:

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

Example:

ArrayList <Integer> Arr=new ArrayList<Integer>();

Similarities Between Java Array and ArrayList:

  • Array and ArrayList are both Data structures used to store data of the same type.
  • Null values can be stored in both Array and ArrayList.
  • Duplicate values can be incorporated into them, but the data type has to be the same.
  • The order of the elements is not preserved.

Now that we have seen the similarities between them, in reality, they are quite different.

Let us discuss the differences between them in detail.

Difference Between Java Array vs ArrayList:

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

1. Nature: Arrays are static data structures in nature. This means, once declared, the size of the array cannot be altered whatsoever. Meanwhile, ArrayList is a dynamic data structure. We do not need to specify any length of ArrayList while declaring it. The size of ArrayList grows in size when and where needed.

2. Implementation: Array is by default incorporated into the JVM. It is a fundamental feature of the Java Programming Language. Meanwhile, ArrayList is present in the Java Collection Framework API. ArrayList is a class that uses Array implicitly to perform various tasks. We can create objects of the ArrayList class and call methods with it. An array on the other hand is a composite data type of java. We cannot call methods with an array except length.

3. Performance: Since ArrayList implicitly uses Array, we might think they perform at the same speed. It is partially correct. ArrayList performs all the basic functionalities with the same speed as an Array. But ArrayList performs various extra functions that perform slowly as it affects the CPU memory. For example, if we resize the ArrayList, it would copy the content of the array to another array then resize it. This slows down the performance of ArrayList.

4. Flexibility: It is one of the main differences between an Array and an ArrayList. ArrayList is far more flexible when compared to an array. An array is a static data structure and is very hard to resize. Meanwhile, ArrayList is very flexible and changes the size very easily and automatically. This makes ArrayList a lot more flexible when compared to arrays. Moreover, we can easily add or remove elements from an ArrayList, whereas arrays do not provide such facilities. It is very hard to remove elements from an array once added.

Example:

Integer intObject[] = new Integer[100];
intObject[0] = new Integer(21); //new Wrapper class object is added to the array object

5. Type of data stored: Arrays can contain any element from primitive data to object of a class. Whereas ArrayList contains only objects, it cannot have primitive data in it. However, there is a workaround to it, we can use autoboxing to store primitive data values. Let us see how using an example:

ArrayList Arr = new ArrayList();
Arr.add(21); //  add 21 int primitive data type

This is possible because ArrayList uses wrapper class objects to store data.

6. Generics: Generics is a feature in java that was added in the year 2004. A major difference between array and ArrayList is that ArrayList supports generics while array does not support generics. The reason being that array is of covariant type while generics are invariant. This is why the compiler doesn’t allow arrays to store generics. ArrayLists do not have such problems.

7. Iteration: Iteration is very important when it comes to data handling, as we have to traverse through the data to find the desired result. The array supports only for loop, for-each loop, while loop, do-while loop. ArrayList on the other hand supports the facility of iterators. We can use ListIterator to iterate through the ArrayList. ArrayList also supports loops, while arrays can never support iterators.

8. Checking the Size: Both arrays and ArrayList have library functions to check their size. Arrays use the length object to check the length. Ar̥rayList uses the size() method to check the size. There is a difference here as well, the length object basically returns the total length of the array, it cannot calculate the amount of filled and empty spaces in the array. The size() method on the other hand returns the current capacity of the ArrayList.

Example:
1.

int Arr[] = new int[100];
arrayLength = array.length; //using the length object

2.

ArrayList ArrL = new ArrayList();
ArrL.add(21);
ArrL.size(); //using the size() method

9. Dimension: This is a very big difference between Arrays and ArrayList. In Array, we can create multidimensional arrays according to our needs. This helps us represent data of graphs, trees and other real-life objects at an ease. But, ArrayList does not have any such feature, Arraylists are a single dimension by default and it cannot be made multidimensional whatsoever. This is a very big drawback in ArrayList when it comes to data representation.

Example:

Integer myArray[][] = new Integer[10][10]; //multidimensional array of size 10x10
myArray[0][0] = new Integer(21);

10. Type Safety: ArrayLists supports generics, thus ArrayList is Type-Safe, i.e, ArrayList allows the compiler to check the object for correctness. Array doesn’t have any such provision, thus arrays are not type-safe. ArrayList supports compile-time checking whereas arrays support Runtime checking. Thus in an array, if the data is incorrect, it will give an ArrayStoreException at runtime.

Example:

String stringArray[] = new String[100];
// creates a string array of size 100
stringArray[0] = new Integer(21);
// throws ArrayStoreException, trying to add Integer object in String[], thus ensuring type safety.

11. Supported Operations: To make the tasks of the programmer easier, ArrayList contains various methods that perform various important functions. Array lists support methods like get(), isEmpty(), indexOf(), replaceAll(), contains(), clear(), removeAll(), which makes programs a lot easier. Arrays on the other hand do not have these methods and everything has to be done manually, making array operations hard to perform.

Array vs Arraylist in Java

PropertyArrayArrayList
DefinitionAn array is a simple data structure with a contiguous memory location, in which data are stored with the same name but different index numbers. The data stored in an array must be of the same type. The size of an array is fixed after declaration.ArrayList is a dynamic data structure that is part of the java collection framework. It also contains elements of the same type. Here we do not need to specify the size of the list.
Static/DynamicArrays are staticArrayList is Dynamic
ResizableFixed LengthResize Possible
Initialization It is mandatory to mention the size of an array during initializationWe do not need to mention the size in the case of ArrayList
PerformanceFasterSlower
Primitive/Generic TypeAn array can store objects and primitive data, but not generics.ArrayList can store Objects and generics but cannot store primitive type data.
IterationOnly Loops are allowedLoops and iterators are allowed
Type-SafetyNot type-safeIt is type-safe
LengthUses length objectUses size() function
Adding ElementsIt uses assignment operator for addingIt uses add() method
Single/Multi-DimensionalBoth single and multidimensional possibleOnly single dimensional allowed

Example of Array and ArrayList using Java Programming:

Now we will discuss a few programs to understand the differences properly.

Code to Understand Array vs ArrayList Differences(Initialization and Access):

import java.util.Arrays;
public class arrVSarrL_Diff
{
   public static void main(String args[]) {
    //Creating and Initializing a Normal Array
    int[] arrN = new int[5];
    arrN[0] = 1;
    arrN[1] = 2;
    arrN[2] = 3;
    arrN[3] = 4;
    arrN[4] = 5;
    //Accessing Array elements
    System.out.println("The first element of Array is: " + arrN[0]);
    System.out.println("The second element of Array is: " + arrN[1]);        
    //Creating an ArrayList with capacity 5 
    ArrayList < Integer > arrL = new ArrayList < Integer > (5);
    // Add elements to ArrayList 
    arrL.add(1);
    arrL.add(2);
    arrL.add(3);
    arrL.add(4);
    arrL.add(5);
    // Accessing the  elements of ArrayList 
    System.out.println("The first element of ArrayList is: " + arrL.get(0));
    System.out.println("The second  element of ArrayList is: " + arrL.get(1));
  }
}

The output of the above code:

The first element of Array is: 1
The second element of Array is: 2
The first element of ArrayList is: 1
The second element of ArrayList is: 2

Code to illustrate that arrays need to have a fixed declared size while ArrayList Doesn’t:

package com.DataFlair.ArrayVsArrayList;
import java.util.ArrayList;
import java.util.Arrays;
public class Fixed_NotFixed
{
     public static void main(String args[]) {
    //Normal arrays in which we need to specify the size for array(here 5) 
    int[] Arr = new int[5];
    Arr[0] = 1;
    Arr[1] = 2;
    Arr[2] = 3;
    Arr[3] = 4;
    Arr[4] = 5;
    System.out.println("Accessing array contents:");
    System.out.println(Arrays.toString(Arr));
    /* We cannot add more elements to array Arr as it is fixed size, otherwise we will get an error(ArrayIndexOutOfBound).*/
    //ArrayList we need not to specify size in ArrayList
    ArrayList < Integer > ArrL = new ArrayList < Integer > ();
    ArrL.add(1);
    ArrL.add(2);
    ArrL.add(3);
    ArrL.add(4);
    // We can add more elements to ArrL, as many as we want.
    System.out.println("Accessing ArrayList contents:");
    System.out.println(ArrL);
  }
}

The output of the above code:

Accessing array contents:
[1, 2, 3, 4, 5]
Accessing ArrayList contents:
[1, 2, 3, 4]

Code to explain that primitive data types are not allowed in ArrayList, Wrapper Class is allowed:

package com.DataFlair.ArrayVsArrayList;
import java.util.ArrayList;
public class primitive_nonprimitive
{
    public static void main(String args[]) {
    // primitive types allowed in an array
    int[] array = new int[3];
    // Objects are also allowed in an array
    primitive_nonprimitive[] array1 = new primitive_nonprimitive[3];
    // Not allowed to add primitive type-below line gives compiler error
    ArrayList < char > arrayList = new ArrayList < char > ();
    // This is Allowed in ArrayList as Wrapper Class is Used
    ArrayList < Integer > arrayList1 = new ArrayList < >();
    ArrayList < String > arrayList2 = new ArrayList < >();
    ArrayList < Object > arrayList3 = new ArrayList < >();
  }
}

The output of the above code:

arraylist error when primitive data used

The compiler doesn’t let us compile the program because ArrayList checks incompatibility at compile time.
ArrayList<char> arrayList = new ArrayList<char>();
^
required: reference
found: char

Conclusion:

As we saw in this article, both array and ArrayList have advantages and disadvantages of their own. In some cases using an array is beneficial while in others ArrayList has an upper hand. It is up to us to judge what to use at what time. In this article, we saw the similarities and dissimilarities between them and we also saw their implementation through java programs.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

No Responses

  1. Kumail says:

    kindly explain more on this topic

    • Data Flair says:

      Hi Kumail,
      Glad to see your comment that you want to explore Java array more. We have already published the detailed Java Array Tutorial. You can take help of this tutorial. I am sure, you will going to like this article. Here is the link for you
      https://data-flair.training/blogs/java-array/
      If you want us to explain any other topic please let us know. We will happy to help you.

Leave a Reply

Your email address will not be published. Required fields are marked *