Java 插入数组并获取null返回值
我正在尝试编写一个插入函数,其中我给出了我想要添加的对象和我想要添加它的索引。出于某种原因,它将对象添加到我想要的位置,但将要替换的数字更改为null 这是家庭作业 即使是一个简单的提示也会有帮助Java 插入数组并获取null返回值,java,arrays,vector,insert,null,Java,Arrays,Vector,Insert,Null,我正在尝试编写一个插入函数,其中我给出了我想要添加的对象和我想要添加它的索引。出于某种原因,它将对象添加到我想要的位置,但将要替换的数字更改为null 这是家庭作业 即使是一个简单的提示也会有帮助 public void insert(Integer obj, Integer index) { if( index > array.length){ throw new IllegalArgumentException("The index you entered
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
每次插入时,您的位置都会向上移动一个位置 所以第一个,
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
iv.insert(2 , 2);
33, 22, 2, null, 44
numItems = 5
第四,44
被添加到末尾,因为i==3==numItems
所以没有效果:
iv.insert(11, 3);
33, 22, null, 44
numItems = 4
五,4>2
,因此在插入之前,再次拉取2
之后的值:
iv.insert(22, 1);
33, 22, null, 44
numItems = 3
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
。这些结果来自哪里?你能解释一下你想做什么吗?array[index]=obj将执行您描述的操作。另外,如果索引与array.length相同,您将获得IndexOutOfBoundsException。作为旁注,我建议您阅读以下内容:。这里不应该使用Integer
。为什么要使用Integer
而不是int