为了账号安全,请及时绑定邮箱和手机立即绑定

kotlin中怎么给list添加元素?

kotlin中怎么给list添加元素?

慕无忌1623718 2019-03-12 09:09:45
kotlin中怎么给list添加元素?
查看完整描述

2 回答

?
慕姐8265434

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位置上已经存在值,那么只能是替换原有值。

 


查看完整回答
反对 回复 2019-03-19
  • 2 回答
  • 0 关注
  • 5765 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信