Advantages of ArrayList over Arrays

Advantages of ArrayList over Arrays

Answer: Below are points:

ArrayList Arrays
ArrayList is dynamically grows list if internal array out of space then its size increases by double Arrays is fixed size list and it cannot be modified once created
Previous to Java version 5 storing primitives type was not allowed only object storage was allowed in ArrayList. After introducing Auto-boxing with Java 5 which allows us to store primitive type which get converted to Objects. On the other hand Arrays can store both Objects and primitive types
ArrayList generics are allowed so that one that one can find what kind of object ArrayList going to store. Use of generics is not allowed in Arrays because Arrays initialize with its type of object it’s going to store.
To get the length you will have to call size method To get the length you will have to call length
There is an overhead related to managing the size of the internal array and more if you try to access its element using casting object This overhead not there in Arrays because initially you define it.
ArrayList is dynamically allocated elements Whereas Arrays is statically allocated elements

Below is example java class:

package com.javahonk.arraylistvector;

import java.util.ArrayList;
import java.util.List;

public class ArrayListAndArray {

    public static void main(String[] args) {

    System.out.println("ArrayList example\n");
    List<String> list = new ArrayList<String>();
    list.add("Java");
    list.add("Honk");
    list.add("Test");
    list.add(null);
    list.add(null);

    for (String string : list) {
        System.out.println(string);
    }

    System.out.println("\nArrays example\n");

    String arrays[] = new String[5];
    arrays[0] = "Java";
    arrays[1] = "Honk";
    arrays[2] = "Test";
    arrays[3] = null;
    arrays[4] = null;

    for (int i = 0; i < arrays.length; i++) {
        String string = arrays[i];
        System.out.println(string);

    }

    }

}

Output:
Advantages of ArrayList over Arrays

That’s it Advantages of ArrayList over Arrays

Leave a Reply

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