将阵列的元素移动到指定的位置
问题描述:
如何将数组的元素移动到Android JAVA上的特定位置。 我们有将阵列的元素移动到指定的位置
int oldPosition, int newPosition
有的像
JSONObject[] tmp = new JSONObject[999];
阵列的JSONObjects
答
如果你只想移动 tmp[newPosition]=tmp[oldPosition];
交换
JSONObject jo= tmp[oldPosition];
tmp[oldPosition]=tmp[newPosition];
tmp[newPosition]=jo;
答
编辑:还有其他的方法,但你可以通过这个问题,以及让您的结果:)
练习:你能理解这个逻辑,并使用JSONObject
型和做需要更改,小心NullPointerExceptions
,处理一切我懒做他们
比方说你有int数组 - >private int array[];
array = new int[]{10,20,30,40,50,60,70,80,90,100};
电话,如果你想交换元素这种方法,
swapNumbers(array,9,1);
。
public int[] swapNumbers(int [] arr, int possition1, int possition2){
int temp = arr[possition2];
arr[possition2] = arr[possition1];
arr[possition1] = temp;
System.out.println("array -->" + Arrays.toString(array));
return arr;
}
出放:阵列[10,,30,40,50,60,70,80,90,20 ]
但不满足你?
需要出放是这样:阵列[10,,20,30,40,50,60,70,80,90]
则可以使用下面的方法
resetUpMyArray(array, array[9],1);
System.out.println("array Finally changed-->" + Arrays.toString(array));
享受,
public int[] resetUpMyArray(int[] inputArray, int deleteMeValue,int addMePosition) {
List resultLinkedList = new LinkedList();
for (int itemValue : inputArray)
if (deleteMeValue == itemValue) {
System.out.println("Do not add this value"+itemValue);
} else {
System.out.println("Do add this value "+itemValue +"position-"+deleteMeValue);
resultLinkedList.add(itemValue);
}
System.out.println("array -as new L.L->" + resultLinkedList);
resultLinkedList.add(addMePosition,deleteMeValue);
System.out.println("array -as new L.L all set->" + resultLinkedList);
array = new int[resultLinkedList.size()];
for (int i = 0; i < resultLinkedList.size(); i++) {
array[i] = (int) resultLinkedList.get(i); // Watch out for NullPointerExceptions!
}
return array;
}
答
下面是两个简单的算法。
开关值:
switch(array, from, to)
tmp = array[to]
array[to] = array[from]
array[from] = tmp
这将会给像
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|--<---->--|
[10, 20, 60, 40, 50, 30, 70, 80, 90, 100]
这将简单地存储,这将是该指数to
在更换是在指数from
的地方的价值观移动和移位值:
这一个将移动一个值,然后移动下一个值。
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|------------^
[10, 20, , 40, 50, 60, 30, 70, 80, 90, 100]
<-----------
[10, 20, 40, 50, 60, 30, 70, 80, 90, 100]
对于这一点,该解决方案是相当的相同,存储值tmp
但每个值转移到填充间隙。此代码将只工作,如果from < to
tmp = array[to]
i = from
while(i < to)
array[i] = array[i+1]; --Shift the value
i = i + 1
array[to] = tmp;
使用临时变量来存储当前值和移动的老位置值的临时变量,然后,在新的位置值移动到老位置终于移到临时值到新的位置。 –
欢迎,请提供您试图向我们展示您在此问题上花费一些时间的代码。当然,你应该首先搜索类似的问题,这是一个简单的算法问题。 – AxelH