【ArrayList源码】get源码及使用

21 篇文章 0 订阅
14 篇文章 0 订阅

1 get源码

   /**
     * Returns the element at the specified position in this list.
     *返回列表中指定位置的元素
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        if (index >= size)//#1
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));//#2

        return (E) elementData[index];//#3
    }
  • 第#1行,如果指定位置大于等于ArrayList数组的长度(指的是数组元素的个数,不是容量),则抛出越界异常
  • 第#3行,返回列表中指定位置的元素。elementData是ArrayList存储数据的数组,ArrayList实际上就是一个数组。

2 get使用

代码:

public class Test {
    
	public static void main(String[] args){
		 ArrayList<String> list = new ArrayList<>();
		 list.add("wo");
		 list.add("ni");
		 list.add("ta");
		 
		 System.out.println(list.get(0));
	}
}

结果:

wo

3 总结

ArrayList的get方法返回ArrayList列表中指定位置的元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值