有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java插入数组并得到一个null返回值

我试图编写一个插入函数,在这里我给出了我想要添加的对象和我想要添加的索引。出于某种原因,它将对象添加到我想要的位置,但将其替换的数字更改为空

这是家庭作业

哪怕是一个简单的提示都会有帮助

public void insert(Integer obj, Integer index) {

 if( index > array.length){
            throw new IllegalArgumentException("The index you entered was out of bounds.");
        }

 for(Integer i = numItems; i > index; i--){
            array[i] = array[i-1];
        }

        array[index] = obj;
        numItems++;         
    }
}

以下是我要插入的内容

iv.insert(44, 2);
iv.insert(33, 0);
iv.insert(22, 1);
iv.insert(11, 3);
iv.insert(2 , 2);

这是我的结果

33
22
2
null
11

共 (1) 个答案

  1. # 1 楼答案

    每次插入时,你的位置都会向上移动一次

    所以第一个numItems < 2

    iv.insert(44, 2);
    null, null, 44
    numItems = 1
    

    第二,同样的效果:

    iv.insert(33, 0);
    33, null, 44
    numItems = 2
    

    第三。现在numItems > i所以值在插入之前会移位:

    iv.insert(22, 1);
    33, 22, null, 44
    numItems = 3
    

    第四,在末尾添加44,因为i == 3 == numItems所以没有效果:

    iv.insert(11, 3);
    33, 22, null, 44
    numItems = 4
    

    第五4 > 2,所以在插入之前,再次将2之后的值拉到一起:

    iv.insert(2 , 2);
    33, 22, 2, null, 44
    numItems = 5
    

    不确定你到底想做什么,但如果你想写一个算法,在覆盖之前向上移动值,你应该做如下操作:

    for(int j = array.length - 1; array[i] != null && j > i; j ){
        array[j] = array[j-1];
    }
    

    但我认为,在现实生活中,如果有LinkedList,你会过得更好