在使用时用错替换值的方法
- 在使用List的
add(int index,E element)
方法时,会导致元素后移,此方法的作用是,往index
下标处插入一个元素,而不是替换。
/**
* Inserts the specified element at the specified position in this list
* (optional operation). Shifts the element currently at that position
* (if any) and any subsequent elements to the right (adds one to their
* indices).
*/
void add(int index, E element);
在此列表中的指定位置插入指定元素(可选操作)。移动当前位于该位置的元素(如果有)和权利的任何后续元素(在其索引)
- 要想替换List中的指定位置的元素,要使用set方法
/**
* Replaces the element at the specified position in this list with the
* specified element (optional operation).
*/
E set(int index, E element);
将此列表中指定位置的元素替换为指定元素(可选操作)。
前提是这个位置已经有元素了,才能替换,否则会报空IndexOutOfBoundsException