在Java数组中移动元素

问题描述 投票:-2回答:3

我在Java中有一个Integer对象数组,如下所示:

{3, 5, 7, 9, 11, null, null, null}

我想将数组的所有非空位置向右移位一个位置,并在位置0处插入“1”。我无法创建新数组或使用其他集合。我最终得到的数组将是:

{1, 3, 5, 7, 9, 11, null, null}

如果不覆盖元素,我将如何做到这一点?

编辑:是的,我已经开始编码。我在这里是因为我被困住了!这是一次尝试。

for(int pos = arr.size; pos >= 1; pos--) {
    arr[pos] = arr[pos - 1];
} 
arr[0] = 1;
java arrays null shift
3个回答
0
投票

您可以通过将每个非空项目向右移动一个位置来在同一个数组中执行此操作。

假设你传递了一个Integers数组:

Integer[] values; // {3, 5, 7, 9, 11, null, null, null};

你可以改变它们:

// for each position from the second-last to the second
for(int i = values.length - 2; i >= 1; i--) {
    // if the current value is not null
    if(values[i] != null) {
        // put it in the next position to the right
        values[i+1] = values[i];
    }
}
// now set the first item to 1
values[0] = 1;

0
投票

您可以使用以下方法..

private void arrayFunction() {
    Integer[] intArray = {3,5,7,11,null,null,null};
    for(int i = intArray.length-1; i >= 0; i--){
        if(i == 0){
            intArray[i] = 0;
        }else{
            intArray[i] = intArray[i-1];
        }

        System.out.println("element "+intArray[i]);
    } 
}

0
投票

这是经过测试的代码,您可以查看它。

 Integer[] values = { 3, 5, 7, 11, null, null, null };
    for (int i = values.length - 2; i >= 0; i--) 
                {
                    values[i + 1] = values[i];
                }
                values[0] = 1;

System.out.println(Arrays.toString(values));
© www.soinside.com 2019 - 2024. All rights reserved.