美文网首页
【ArrayList源码】get源码及使用

【ArrayList源码】get源码及使用

作者: 秀叶寒冬 | 来源:发表于2019-07-22 20:17 被阅读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列表中指定位置的元素。

相关文章

网友评论

      本文标题:【ArrayList源码】get源码及使用

      本文链接:https://www.haomeiwen.com/subject/ttjglctx.html