关于向在第index个位置插入一个新的元素e的数组边界问题
来源:1-4 向数组中添加元素
Mosea
2023-12-24 16:57:26
// 在第index个位置插入一个新的元素e
public void add(int index, int e) {
if (size == data.length) {
throw new IllegalArgumentException("AddLast failed. Array is full.");
}
if (index < 0 || index > size) {
// 为何 index 是 <=size? 前一个if已经保证 size < capacity。即使 index == size ,也可以保证index <capacity。
throw new IllegalArgumentException("AddLast failed. Require index >= 0 and index <= size.");
}
// 如果index = size,则不进入这个for循环
for (int i = size - 1; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = e;
size++;
}
这是我在写这段代码的时候,一直在思考数组边界的问题,这么写会不会造成数组越界,分析如上。
1回答
liuyubobobo
2023-12-28
我不很确定你的问题是什么,如果我没有理解错,你的问题是,为什么 index 可以等于 size?
这是因为,如果一个数组已经有 size 个元素,可以插入的位置有 size + 1 个。
比如一个数组是 0 1 2 3 一共四个元素,插入 x,对应如下:
插入在 index = 0 的位置,插入结果是 x 0 1 2 3;
插入在 index = 1 的位置,插入结果是 0 x 1 2 3;
插入在 index = 2 的位置,插入结果是 0 1 x 2 3;
插入在 index = 3 的位置,插入结果是 0 1 2 x 3;
插入在 index = 4 的位置,插入结果是 0 1 2 3 x;
继续加油!:)
相似问题