【ArrayList源码】get源码及使用

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列表中指定位置的元素。

发布了107 篇原创文章 · 获赞 142 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/u013293125/article/details/96893783