这是我的数组:
int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
假设我想将myArray [3](可以是任何元素)和myArray [6](同样如此)移动到数组的前面并重新排列后面,我该怎么做? 例如:
这个:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
转化为:
{3, 6, 0, 1, 2, 4, 5, 7, 8, 9}
这是我的数组:
int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
转化为:
{3, 6, 0, 1, 2, 4, 5, 7, 8, 9}
将索引x
移动到最前面,您需要执行以下操作:
x
中的值System.arrayCopy
将从0
到x - 1
索引之间的所有内容向上移动一个索引0
的值例如:
public void moveToHead(int[] values, int index)
{
// TODO: Argument validation
int value = values[index];
System.arraycopy(values, 0, values, 1, index - 1);
values[0] = value;
}
System.arraycopy
会适当地处理复制:moveToHead
调用将更加简单。您需要注意顺序 - 例如,如果您想首先将索引6
移动到头部,则需要移动索引4而不是索引3,以考虑第一次移动。Arrays.asList
获取的列表既不允许add
也不允许remove
。将其替换为new ArrayList<Integer>(Arrays.asList(myArray))
,然后它应该可以工作。 - gustafc