将数组元素移动到特定位置

时间:2016-12-29 07:33:29

标签: java arrays

如何在Android JAVA上将数组元素移动到特定位置。 我们有

int oldPosition, int newPosition

和某些人一样

JSONObject[] tmp = new JSONObject[999];

JSONObjects

的数组

3 个答案:

答案 0 :(得分:0)

如果你想移动 tmp[newPosition]=tmp[oldPosition];

交换

JSONObject jo= tmp[oldPosition]; tmp[oldPosition]=tmp[newPosition]; tmp[newPosition]=jo;

答案 1 :(得分:0)

编辑:还有其他方法,但您也可以通过此方式获取结果:)

练习:您可以理解这种逻辑并使用{​​{1}}类型并进行必要的更改,注意JSONObject,处理我懒得做的所有事情

假设你有int数组 - > NullPointerExceptions

private  int array[];

如果要交换元素,请调用此方法

 array = new int[]{10,20,30,40,50,60,70,80,90,100};

swapNumbers(array,9,1);

out put:array [10, 100 ,30,40,50,60,70,80,90, 20 ]

但那不满足你?

你需要像这样:阵列[10, 100 ,20,30,40,50,60,70,80,90]

您可以使用以下方法

 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;
}

享受,

resetUpMyArray(array, array[9],1);
System.out.println("array Finally changed-->" + Arrays.toString(array));

答案 2 :(得分:0)

这是两个简单的算法。

切换值:

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;
相关问题