Java中,数组中的元素转移 [英] Java, Shifting Elements in an Array
问题描述
我在Java对象的数组,我想一个元素拉至顶部,一个休息下移。
I have an array of objects in Java, and I am trying to pull one element to the top and shift the rest down by one.
假设我有大小为10的数组,而我试图拉第五元素。第五元素进入位置 0
从0到5的所有元素将依次下移。
Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0
and all elements from 0 to 5 will be shifted down by one.
这个算法不正确转移的元素:
This algorithm does not properly shift the elements:
Object temp = pool[position];
for (int i = 0; i < position; i++) {
array[i+1] = array[i];
}
array[0] = temp;
我怎么做是正确的?
How do I do it correctly?
推荐答案
假设你的数组是{} 10,20,30,40,50,60,70,80,90,100
Assuming your array is {10,20,30,40,50,60,70,80,90,100}
你的循环的作用是:
迭代1:阵列[1] =阵列[0]; {} 10,10,30,40,50,60,70,80,90,100
Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}
迭代2:数组[2] =阵列[1]; {} 10,10,10,40,50,60,70,80,90,100
Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}
你应该做的是
Object temp = pool[position];
for (int i = (position - 1); i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
这篇关于Java中,数组中的元素转移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!