我正在尝试编写一个插入函数,其中我给出了我想要添加的对象以及我想要添加它的索引。出于某种原因,它将对象添加到我想要的位置,但将其替换的数字更改为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
答案 0 :(得分:0)
每次插入时,您的位置都会向上移动一次。
所以第一个,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
。