Arjun Sharma
Arjun Sharma

Reputation: 71

How to add a element to the end of a array?

So I am trying to add an element to the end of an array. What I've tried to do is make a new array that is bigger to accommodate the new array. And then I tried to add an element to the array. The only problem is that once an element, all the elements of the array get copied over.

accountId = Arrays.copyOf(accountId, accountId.length + 1);
        money = Arrays.copyOf(money, money.length + 1);

        for (int i = 0; i < accountId.length; i++) {
            accountId[i] = id;
        }

        for (int i = 0; i < money.length; i++) {
            money[i] = opBalance;
        } 

I Would appreciate any help!

Upvotes: 0

Views: 747

Answers (2)

Ahmed Abubaker
Ahmed Abubaker

Reputation: 139

this example to insert the elements an array at the end , in this array we have add element in an unsorted array in the end array of integers

  class insertion {

  //fuction to insert a given key in the array.
  //this function return n + 1 
  //if isertion is successful , else return n
      static int insertSorted(int arr[] , int n , int key , int capacity) {

          //can not insert more elements if n is more
          //than or equal capacity
          if(n >= capacity) {
              return n;
          
             }  
               
         arr[n] = key;

         return (n + 1);                     

   }

  public static void main (String args[]) {
     int arr[] = new int[20]       
     arr[0] = 12;          
     arr[1] = 16;
     arr[2] = 20;
     arr[3] = 40;
     arr[4] = 50;
     arr[5] = 70;
   
    int capacity = 20;
    int n = 6;       
    int i , key = 26;
     
   System.out.print("before insertion: ");  
    for(i = 0; i < n; i++) {
        // before inserting
        System.out.print(arr[i] , "  ");

      }

    // inserting key
    n = insertSorted(arr , n , key , capacity); 
    System.out.print(\n After inserting: " );

        for(i = 0; i < n; i++) {
            //after inserting
            System.out.print(arr[i] , " "); 

         }
    
   }



}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

You don't need loops after you copy the arrays. Just set the last element. Also, I would prefer a Plain Old Java Object (POJO) to two parallel arrays.

accountId = Arrays.copyOf(accountId, accountId.length + 1);
money = Arrays.copyOf(money, money.length + 1);
accountId[accountId.length - 1] = id;
money[money.length - 1] = opBalance;

Upvotes: 2

Related Questions