2 回答

TA貢獻1813條經驗 獲得超2個贊
public interface List<E> extends Collection<E>是接口,不能直接使用,必須由它的實現子類才能使用。
set(index, obj);方法某些時候可以實現添加新元素。
以下是ArrayList的set源碼部分:
/**
* Replaces the element at the specified position in this list with
* the specified element.
*使用element替代list中指定位置的element
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
RangeCheck(index);//邊界查詢,判斷index是否越界
E oldValue = (E) elementData[index];//取出index位置的元素
elementData[index] = element;//替換指定位置的元素
return oldValue;//返回被替換的元素
}
set方法的含義:用指定的元素替代此列表中指定位置上的元素。如果指定位置是為空,那么就相當于add(int index, E element)方法,添加新元素到list中,如果這個index位置上已經存在值,那么只能是替換原有值。
- 2 回答
- 0 關注
- 5884 瀏覽
添加回答
舉報