Fix the index out of bound check in my_list.

This commit is contained in:
Yudong Jin
2023-01-30 17:50:07 +08:00
parent 15c798046a
commit ddd5562b60
11 changed files with 90 additions and 98 deletions

View File

@ -33,14 +33,14 @@ class MyList {
/* 访问元素 */
public int get(int index) {
// 索引如果越界则抛出异常,下同
if (index >= size)
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("索引越界");
return nums[index];
}
/* 更新元素 */
public void set(int index, int num) {
if (index >= size)
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("索引越界");
nums[index] = num;
}
@ -57,7 +57,7 @@ class MyList {
/* 中间插入元素 */
public void insert(int index, int num) {
if (index >= size)
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("索引越界");
// 元素数量超出容量时,触发扩容机制
if (size == capacity())
@ -73,7 +73,7 @@ class MyList {
/* 删除元素 */
public int remove(int index) {
if (index >= size)
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("索引越界");
int num = nums[index];
// 将索引 index 之后的元素都向前移动一位