Add Elements to Array and ArrayList

JavaJavaBeginner
Practice Now

Introduction

An array is a collection of similar data types in Java with a fixed size, while an ArrayList is a dynamic collection of similar data types. This lab will show you how to add elements to an array and ArrayList.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/generics -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/arraylist -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/classes_objects -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/class_methods -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/modifiers -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/oop -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/packages_api -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/wrapper_classes -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/identifier -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/arrays -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/data_types -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/for_loop -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/if_else -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/operators -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/output -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/strings -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/variables -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/arrays_methods -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/object_methods -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} java/system_methods -.-> lab-117386{{"`Add Elements to Array and ArrayList`"}} end

Append elements to an array:

To append elements to an array, you need to follow the given steps:

  • Create an array of the larger size
  • Copy the elements from the old array to the new array using a loop
  • Add the new element to the end of the new array

Here is the code for appending elements to an array:

~/project/ArrayAppend.java

import java.util.Arrays;

public class ArrayAppend {
   public static int[] appendToArray(int[] oldArr, int elementToAdd) {
      int[] newArr = Arrays.copyOf(oldArr, oldArr.length + 1);
      newArr[newArr.length - 1] = elementToAdd;
      return newArr;
   }

   public static void main(String[] args) {
      int[] arr = {1, 2, 3, 4, 5};
      System.out.println("Initial Array: " + Arrays.toString(arr));
      arr = appendToArray(arr, 6);
      arr = appendToArray(arr, 7);
      arr = appendToArray(arr, 8);
      System.out.println("After adding elements: " + Arrays.toString(arr));
   }
}

To run the code, open the terminal in the project folder, then compile and run the code with the following commands:

javac ArrayAppend.java
java ArrayAppend

After running the code, you will get the following output:

Initial Array: [1, 2, 3, 4, 5]
After adding elements: [1, 2, 3, 4, 5, 6, 7, 8]

Append elements to an ArrayList:

To append elements to an ArrayList, you need to follow the given steps:

  • Create an ArrayList
  • Use the add() method to add elements to the ArrayList

Here is the code for appending elements to an ArrayList:

~/project/ArrayListAppend.java

import java.util.ArrayList;

public class ArrayListAppend {
   public static void main(String[] args) {
      ArrayList<Integer> arrList = new ArrayList<Integer>();
      arrList.add(1);
      arrList.add(2);
      arrList.add(3);
      System.out.println("Initial ArrayList: " + arrList);
      arrList.add(4);
      arrList.add(5);
      System.out.print("After adding elements: " + arrList);
   }
}

To run the code, open the terminal in the project folder, then compile and run the code with the following commands:

javac ArrayListAppend.java
java ArrayListAppend

After running the code, you will get the following output:

Initial ArrayList: [1, 2, 3]
After adding elements: [1, 2, 3, 4, 5]

Insert elements to an array:

To insert elements to an array, you need to follow the given steps:

  • Create an array of the larger size
  • Shift the elements of the old array to the right of the new array until the new element is inserted
  • If the index is out of range, throw an IndexOutOfBoundsException

Here is the code for inserting elements to an array:

~/project/ArrayInsert.java

import java.util.Arrays;

public class ArrayInsert {
   public static int[] insertAtIndex(int[] arr, int elementToAdd, int index) {
      if (index > arr.length || index < 0) {
         throw new IndexOutOfBoundsException("Index is out of range!");
      } else {
         int[] newArr = new int[arr.length + 1];
         for (int i = 0, j = 0; i < arr.length; i++, j++) {
            if (i == index) {
               newArr[j++] = elementToAdd;
            }
            newArr[j] = arr[i];
         }
         return newArr;
      }
   }

   public static void main(String[] args) {
      int[] arr = {1, 2, 3, 4, 5};
      System.out.println("Initial Array: " + Arrays.toString(arr));
      arr = insertAtIndex(arr, 6, 2);
      System.out.println("After inserting at index 2: " + Arrays.toString(arr));
   }
}

To run the code, open the terminal in the project folder, then compile and run the code with the following commands:

javac ArrayInsert.java
java ArrayInsert

After running the code, you will get the following output:

Initial Array: [1, 2, 3, 4, 5]
After inserting at index 2: [1, 2, 6, 3, 4, 5]

Insert elements to an ArrayList:

To insert elements to an ArrayList, you need to follow the given steps:

  • Create an ArrayList
  • Use the add() method to add elements to the ArrayList
  • Use the overloaded version of the add() method to insert elements to the ArrayList

Here is the code for inserting elements to an ArrayList:

~/project/ArrayListInsert.java

import java.util.ArrayList;

public class ArrayListInsert {
   public static void main(String[] args) {
      ArrayList<Integer> arrList = new ArrayList<Integer>();
      arrList.add(1);
      arrList.add(2);
      arrList.add(3);
      System.out.println("Initial ArrayList: " + arrList);
      arrList.add(1, 5);
      arrList.add(3, 6);
      System.out.print("After inserting elements: " + arrList);
   }
}

To run the code, open the terminal in the project folder, then compile and run the code with the following commands:

javac ArrayListInsert.java
java ArrayListInsert

After running the code, you will get the following output:

Initial ArrayList: [1, 2, 3]
After inserting elements: [1, 5, 2, 6, 3]

Summary

This lab has shown you how to add elements to an array and ArrayList in Java. We have learned how to append and insert elements to an array and ArrayList. While appending is easy, inserting can be a bit complex in the case of arrays, but ArrayList has a straightforward insert method. Always make sure to stay within the bounds of the array or ArrayList, otherwise, IndexOutOfBoundsException will occur.

Other Java Tutorials you may like