Java:移动数组中的项目 [英] Java: moving items in array
问题描述
我希望在数组内移动东西.
I'm looking to move things around within an Array.
我希望能够将给定数组中的最后一个项目移动到一个位置,同时将当前位置中的项目向右移动.我希望它从第一个位置移动到第二个位置,等等,而不替换当前存在的项目.
I want to be able to move the last item within the given Array to a spot while moving those in the current location to the right. I want it to move from the first spot to the second, etc. without replacing the item that is currently there.
例如)
a,b,c,d,e
假设我想移动到3" - 然后它会变成
Say I want to move to "3" - it would then become
a,b,c,e,d
我目前有以下几点:
public static void moveLastup(String[] stuff, int position)
{
String y = stuff[stuff.length-1];
for (int x = stuff.length-1; x > position; x--)
list[x] = list[x-1];
stuff[position] = y;
}
抱歉,我认为我还不够清楚.我希望能够做的是给出这种方法,我应该能够将最后一块移动到任何地方.
edit: sorry I don't think I was clear enough. What I want to be able to do is given this method, I should be able to move the last piece anywhere.
for (int pos = 0; pos < stuff.length; pos++)
{
moveLastup(list,pos);
showList(list);
}
现在,当我执行此操作时,它只会获取 for 循环中下一个列表中的最后一项例)
Now when I execute this, it simply takes the last item in the next list in the for loop ex)
e,a,b,c,d
e,d,a,b,c
e,d,c,b,a
我希望它显示
e,a,b,c,d
a,e,b,c,d
a,b,e,c,d
推荐答案
这里有一个更高效简洁的解决方案,依赖于原生实现的System.arraycopy
:
Here's a more efficient and concise solution, relying on the natively implemented System.arraycopy
:
public static void moveLastup(String[] arr, int pos) {
String last = arr[arr.length-1];
// Copy sub-array starting at pos to pos+1
System.arraycopy(arr, pos, arr, pos + 1, arr.length - pos - 1);
arr[pos] = last;
}
还有一些测试代码:
public static void main(String[] args) {
String[] test = { "one", "two", "three", "four", "five" };
// Move "five" to index 2
moveLastup(test, 2);
// [one, two, five, three, four]
System.out.println(Arrays.toString(test));
}
<小时>
关于您的您正在使用和修改原始数组.如果您想在每个 moveLastup
中重新开始",您需要处理一个副本.此代码段打印您想要的内容:
Regarding your edit: You're working with and modifying the original array. If you want to "start over" in each moveLastup
you need to work on a copy. This snippet prints what you want:
String[] list = { "a", "b", "c", "d", "e" };
for (int pos = 0; pos < list.length; pos++) {
String[] tmpCopy = list.clone();
moveLastup(tmpCopy, pos);
showList(tmpCopy);
}
输出:
[
e
, a, b, c, d]
[a,
e
, b, c, d]
[a, b,
e
, c, d]
[a, b, c,
e
, d]
[a, b, c, d,
e
]
这篇关于Java:移动数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!