Arrays and ArrayList in Java – Difference and complete guide

Arrays and ArrayList in Java – Difference and complete guide

If you are new to programming or you are starting to code in Java then, you must have come across the terms Arrays and ArrayList. Though both the terms seem identical, there is a lot of difference between them.

In this blog, we will look at both Arrays and ArrayList. we will learn their implementation and differences. As a result of which you will nurture the instinct of using the right one according to the need of the problem.

Arrays

An array is a contiguous collection of a fixed number of data elements of the same data type. Array Elements have indexes starting from 0. This makes it easy to access and change random elements from an array. One of the main advantages of using Arrays is that we use a single name for multiple values to group them. This improves the readability of the code and makes it more flexible.

Array Declarations

One-Dimensional Arrays: A One-Dimensional Array at its core is a list of variables of the same data type. We create an array variable to use an array.

SYNTAX:

type variable_name;

Here type declares the data type. It represents the type of data we store as array elements. Variable Name is the name we use to access and modify array elements through their indexes. The variable name represents the array we create.

Valid One-Dimensional Array Declarations:

int[] arr;
int arr[];
int []arr;

– All the above three Array declarations are correct but the first one is the most popular since it separates type and variable names and is also a standard Java practice.

– We can not specify the type of Array during declaration.

Multidimensional Arrays: In Java, Multidimensional arrays are arrays of arrays. Just like 1-D arrays, we declare multi-dimensional arrays by specifying Data type and variable alongside to represent the array.

Valid 2-D Array Declarations:

int[][] arr;
int [][]arr;
int arr[][];
int[] arr[];
int[] []arr;
int []arr[];

Array Construction

Creation of One-Dimensional Arrays

Every array in Java is an object. Although we have declared the array variable, no array exists. You must use a new keyword to allocate memory to the array variable.

int[] week_days = new int[5];

Graphical representation of Single Dimensional Array

  • At the time of construction of the Array, you must specify the size otherwise you will get a compilation error.

  • It is legal to have an array of size 0 in Java.

  • If we enter the size as a negative integer, we will get a runtime exception saying NegativeArraySizeException.

  • byte, short, int, and char are data types we use for specifying the size of arrays.

Creation of 2-D Arrays

In Java we do not implement arrays in matrix form but as arrays of arrays concept. The major advantage of this implementation is improvement in memory utilization.

int[][] array = new int[3][];
array[0] = new int[2];
array[1] = new int[1];
array[2] = new int[3];

Graphical Representation of 2-D Arrays

Array Initialization

When we create an array it is initialized with default values. Later we can override those values as per our needs.

int[] arrExample = new int[3];
arrExample[0] = 7;
arrExample[1] = 13;
arrExample[2] = 19;

Array after initialization

Array after initialization

Note: If we try to access an element through an index out of range i.e, size of the array then we’ll get runtime exception ArrayIndexOutOfBoundsException.

Array Declaration, Construction and Initialization in Single Line

We can declare, create and initialize an array in a single line.
Example:

int[] counter = {1,2,3,4};
char vowels = {'a','e','i','o','u'};
string[] str = {"Code","Damn","Community"};

We can also initialize Multidimensional arrays in the same way too.

int[][] matrixExample = {{12,17,23} , {7,9,2}};
int[][][] threeDMatrix = {{{10,20,30},{40,50},{60}} , {{70,80},{90,100},{110}}}

length() vs length

  1. length – It is the final variable used to find the size of an array.

  2. length() – it is the final method (function) used to find the number of characters in a string.

// Java program to show difference between length
// and length()
public class Example {
// This is the Main Function
    public static void main(String[] args)
    {
        // Here arr is the array name of type int
        int[] arr = new int[4];
        System.out.println("The size of the array arr is "
                        + arr.length);

        // Here name is a string object
        String name = "Codedamn";
        System.out.println("The size of the String name is "
                        + name.length());
    }
}

length vs length()

ArrayList

Limitations of Array

Although object arrays are very useful data structures. They have some limitations due to which we can not use them every time. For instance:

  • The size of the arrays is fixed. Increment or decrement is not possible later. Hence while using arrays, we should know the size in advance which is not always possible

  • Arrays are not based on some other data structure. Due to this not a lot of readymade method support is not present for different needs.

ArrayList and its advantages

ArrayList is a class in Java that implements Dynamic Arrays. This means there is no limit to the size of elements we can enter. We can compare Java ArrayList with Vectors in C++. We can resize ArrayList as the program move forward as per our need.

ArrayList overcomes the limitations of the array because we can change its size as per our needs. This collections class is built using other data structures. So readymade method support is available to perform various operations on data elements of List.

ArrayList implements the RandomAccess interface. This allows us to access random elements with the same ease and speed. Hence if retrieval is our most used operation then the best suitable data structure is an ArrayList.

Note: if we are to frequently insert and delete an element from the middle of a List, then LinkedList is a more suitable option than ArrayList.

ArrayList is part of the collection framework. It inherits the AbstractList class and implements the List interface which is a child interface of the collection.

Java ArrayList Class Hierarchy

Important Points to remember about ArrayList:

  • Duplicate objects can be inserted in an ArrayList.

  • The insertion order is preserved in an ArrayList.

  • Just like an array we can access and perform any operation on the random element of the List using the index array index.

  • Java ArrayList also allows Null insertion.

  • It can hold both Homogenous and Heterogenous objects.

  • ArrayList does not use primitive Data types. We must use Wrapper classes because ArrayList can only hold class objects. We are creating wrapper class objects to use a collection of primitive data types

Constructors in ArrayList

Similar to how we create an array object to use it. We also need to create an object of the ArrayList class using a new keyword. But we also use constructors in the statement for List creation.

The Constructors of the class are as follows:

1. ArrayList(): This constructor creates an empty List. Let us take an example by creating an ArrayList of the name NumsExample.

ArrayList NumsExample = new ArrayList();

2. ArrayList(Collection c): This constructor creates a list that is initialized with the elements from another collection c. Let us take an example to create an ArrayList of name NumsExample which contains the elements from the collection c:

ArrayList NumsExample  = new ArrayList(c);

3. ArrayList(int capacity): This constructor creates a list by specifying the initial size at the time of declaration. Let us take an example to create an ArrayList of name NumsExample with an initial capacity of N:

ArrayList NumsExample  = new ArrayList(N);

Basic Operations on ArrayList

1. Adding elements to a List.
2. Modifying elements from a List.
3. Deleting an element from a List.
4. Iterating through List elements.

  • Operation 1: Adding Elements to a List

    We use the add() method to add a new element to the List. It is an overloaded function that works on different parameters. They are as follows:

    add(object): This method is used to add a new element at the end of the List.
    add(int index, object): This method is used to add a new element at a specified index of the List.

// Java Program to Add elements to An ArrayList
// Importing all utility classes
import java.util.*;

// Main class
class CodeDamn {
// This is start of Main Function 
    public static void main(String args[])
    {
        // Creating a List of type : string
        ArrayList<String> listName = new ArrayList<>();

        // Adding elements to List
        // Custom inputs
        listName.add("Code");
            listName.add("Community");

        // Here we are mentioning the index
        // at which it is to be added
        listName.add(1, "Damn");

        // Printing all the elements in an ArrayList
        System.out.println(listName);
    }
}
Code language: Java (java)

Entering Elements in an ArrayList

Entering Elements in an ArrayList

  • Operation 2: Modifying Elements

    If we want to change an already existing element in the List then we can use the set() method. It takes the index of the elements to be changed and updated value as arguments.

// Java Program to change elements in an ArrayList
// Importing all utility classes
import java.util.*;

// Main class
class CodeDamn {
// This is the start of Main Function
    public static void main(String args[])
    {
        // Creating a List of type: string
        ArrayList<String> listName = new ArrayList<>();

        // Adding elements to List
        listName.add("Code");
            listName.add("Community");

        // Adding an element to a specific position 
        listName.add(1, "Damn");

                // Printing all the List elements 
        System.out.println("ArrayList before change: " + listName);

                // Modifying Element at index 2
                listName.set(2,"Classroom");

        // Printing all the List elements after change
        System.out.println("ArrayList after change: " + listName);
    }
}
Code language: Java (java)

Modifying Elements

Modifying Elements

Operation 3: Removing an element from ArrayList

To remove an element from the List, we use the remove() method. It is an overloaded function that operates on different parameters. They are as follows:

remove(): this method removes the object from the List. In the case of duplicates, the function removes the first occurrence of the object.
remove(int index): this method is used to remove an object from a specific index of the List.

// Java Program to remove elements from a ArrayList
// Importing all utility classes
import java.util.*;

// Main class
class CodeDamn {
// This is the start of the Main Function
    public static void main(String args[])
    {
        // Creating a List of type: string
        ArrayList<String> listName = new ArrayList<>();

        // Adding List Elements
        listName.add("Code");
                listName.add("Damn");
            listName.add("Community");

                // Printing all the List elements
        System.out.println("ArrayList before change: " + listName);

                // Deleting Element at index 2
                listName.remove(2);
                // Deleting "Damn" from List (using Object itself))
                listName.remove("Damn");

        // Printing all the List elements
        System.out.println("ArrayList after change: " + listName);
    }
}
Code language: Java (java)

Removing an element from ArrayList

Removing an element from ArrayList

  • Operation 4: Iterating through List elements

    There are many ways to iterate through a list but we will use For Loop to run through all the indexes and then use the get() method to access the element at that index.

// Java Program to iterate through elements in an ArrayList
// Importing all utility classes
import java.util.*;

// Main class
class CodeDamn {
    public static void main(String args[])
    {
        // Creating an Array of string type
        ArrayList<String> listName = new ArrayList<>();

        // Adding elements to ArrayList
        // Custom inputs
        listName.add("Code");
                listName.add("Damn");
            listName.add("Community");

               // Iterating using For Loop
               for(int i=0;i<listName.size();i++){
                  System.out.print(listName.get(i)+" ");
               }
               // Line Break
               System.out.print();

               // Iterating using For-Each Loop
               for(String s: listName){
                  System.out.print(s +" ");
               }
    }
}
Code language: Java (java)

Iterating through elements in ArrayList

ArrayList Methods

Other useful methods that help to make our code clean and efficient are as follows:

  • addAll(Collection c): this method is used to add all the elements from a collection to the end of an existing List.

  • addAll(int index, Collection c): All the elements from the collection c are added from the specified index onwards in the List.

  • clear(): This method is used to remove all the elements from the List.

  • clone(): This method returns a copy of the ArrayList.

  • contains?(object): This method returns a boolean value. True if the object is present in the ArrayList else it returns false.

  • size(): This method returns the size I,e., the number of elements present in the list.

  • indexOf(object): This method returns the index of the first occurrence of the object. It returns -1 if the list does not contain the object.

  • lastIndexOf(): This method returns the last index of the object. It returns -1 if the list does not contain the object.

Conclusion

If you want to learn in detail about Java’s Collection Framework and all the methods of Arrays and ArrayList then you can read the Official Documentation:
docs.oracle.com/javase/tutorial/java/index...