Noah
Noah

Reputation: 3

Copy an array into the end of a larger array

I want to copy an array into a larger array, but instead of starting at the first element or a specified element, such as System.arraycopy(), I want it to start at the last element and move backward.

int [] ary1 = new int[5] {1,2,3,4,5};
int [] ary2 = new int [10];

and I want the elements in ary2 to equal

0,0,0,0,0,1,2,3,4,5

or

null,null,null,null,null,1,2,3,4,5

Upvotes: 0

Views: 1146

Answers (2)

Ashraful041
Ashraful041

Reputation: 155

This will work 
int [] ary1 = {1,2,3,4,5};
    int [] ary2 = new int [10];
    int y = ary2.length-1;
    for (int i = ary1.length-1; i >=0; i--) {
        ary2[y]=ary1[i];
        y--;
    }

Upvotes: 0

SilverNak
SilverNak

Reputation: 3381

You can use the method System.arrayCopy() for that purpose. Since you use an array of primitive int type, the resulting array will be [0, 0, 0, 0, 0, 1, 2, 3, 4, 5]

System.arraycopy(ary1, 0, ary2, 5, ary1.length);

The arguments are:

  1. Source-array
  2. Start-position in source-array
  3. Destination-array
  4. Start-position in destination-array
  5. Number of elements to copy

Upvotes: 2

Related Questions