Reputation: 3
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
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
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:
Upvotes: 2