I am completely newbie to java. I want to reverse an array. So I have created one new empty array with the size of input array. Now I want to push elements from input array to new array by accessing elements of input array from backside.
There might be methods to reverse the array, but I don't want to use them. I want to write the logic to reverse.
So, here my question is, is there any method to push an element to array, like arrayOne.push(arrayTwo[index])
public int rotateArray(int[] a) {
int[] intArray=new int[a.length];
for(i=a.length-1;i--){
intArray.push(a[i]) // How to push the element to array here...
}
}
Before asking this question, I researched in Google and checked some already existed stackoverflow questions, but didn't help me...
In Java, Arrays
do not work as Stack
. To reverse, you could do something like below:
public int[] rotateArray(int[] a) {
int n = a.length;
int[] intArray=new int[n];
for(int i=n;i>0;i--){
intArray[n-i] = a[i-1];
}
return intArray;
}
Arrays
have fixed size. You can also use List
with Collections.reverse