Add Integers to an Array

Hiten Kanwar Jul 11, 2021 May 29, 2021 Java Java Array
  1. Use Another Array to Add Integers to an Array in Java
  2. Use the add() Function to Add Integers to an Array in Java
Add Integers to an Array

In Programming, arrays are a common data structure and store similar types of elements in a contiguous memory location.

This tutorial will discuss different ways to add integers to an array in Java.

Use Another Array to Add Integers to an Array in Java

In Java, we can edit the elements of an array, but we cannot edit the size of an array. However, we can create an array of greater size to accommodate the additional elements. This method is not memory efficient.

If we have an array containing five elements and add two more elements, we can create another array for the size of seven elements containing the original and additional elements.

We can implement this in the following code.

public class ABC{
public static void main(String []args){
    int[] arr1 = {2,3,5,7,8}; // array of size 5
    int[] arr2 = new int[7]; // new array declared of size 7
    for(int i = 0 ; i < 5 ; i++) {
        // adding all the elements of orignal array arr1 to new array arr2
        arr2[i] = arr1[i]; 
    }
    arr2[5] = 10; // added value 10 to 6th element of new array
    arr2[6] = 12; // added value 12 to 7th element of new array
    System.out.print(arr2[6]); // printing element at index 6
}
}

Output:

12

In the above code, we created arr2, which contains all arr1 and the new additional integers.

Use the add() Function to Add Integers to an Array in Java

The add() function in Java can add elements in different collections such as lists and sets, but not for arrays because they have a fixed length, and we cannot alter their size. However, we can use this function to add elements by creating a list of arrays.

An ArrayList has several advantages over arrays as there is no restriction over the size of the list. We can indefinitely keep adding elements to lists. However, it is not as fast as arrays.

For example,

import java.util.ArrayList;
public class ABC{
public static void main(String []args){
    int[] arr = {2,4,5,6}; // created an array of size = 4
    // creating an ArrayList
    ArrayList<Integer> al = new ArrayList<Integer>(); 
    for(int x: arr) {
        al.add(x); // adding each element to ArrayList
    }
    al.add(10); // now we can add more elements to the array list
    al.add(18);
    System.out.print(al);
}
}

Output:

[2,4,5,6,10,18]

Note that one should import the java.util.ArrayList package to work with ArrayList.

Related Article - Java Array

  • Concatenate Two Arrays in Java
  • Convert Byte Array in Hex String in Java
  • Remove Duplicates From Array in Java
  • Count Repeated Elements in an Array in Java
  • Natural Ordering in Java
  • Slice an Array in Java