我是 java 的新手。我想反转一个数组。所以我创建了一个新的空数组,其大小为输入数组的大小。现在我想通过从背面访问输入数组的元素将元素从输入数组推送到新数组。
可能有反转数组的方法,但我不想使用它们。我想写逻辑来反转。
所以,我的问题是,是否有任何方法可以将元素推送到数组,例如 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...
}
}
在问这个问题之前,我在谷歌上进行了研究并检查了一些已经存在的stackoverflow问题,但没有帮助我......
最佳答案
在 Java 中,Arrays
不像 Stack
那样工作。
要反转,您可以执行以下操作:
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;
}
数组
具有固定大小。您也可以使用 List
与 Collections.reverse
关于java - 如何在java中将元素推送到空的固定大小数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416011/