0.0
list不是不规定长度的吗,为什么还会出现下标学界
list不是不规定长度的吗,为什么还会出现下标学界
2016-12-15
我简单回答一下。
add()方法中的数字,指的是添加位置。
get()方法中的数字,指的是要调用的位置。
add()方法的使用。初次往里面添加的话,添加位置只能是0位置,0可以省略不写的。 当第二次需要添加的时候,有两个添加位置,0位置和1位置。当你添加到0位置的时候,也就是把原本0位置存在的属性值,挤到了1位置。你也可以添加到1位置,这个时候1可以省略不写。每一次的添加都是对位置的从新排序。 当你需要第三次添加的时候,有0位置,1位置,2位置这样3个选择。选择最后一个位置的话,也就是2位置,2可以省略不写。选择1位置或者0位置就是把需要添加的属性值插进去,把原本存在的属性值挤到下一位。 上面所说的添加,指的是每次添加一个属性值。
get()方法的使用。括号里面的数字是几调用的就是几号位置的属性值。记住每一次添加都是对前面属性值的从新排序,调用几号位置,输出的就是几号位置的属性值。
这样应该是简单易懂吧
ArrayList的add(int index, E element)方法的实现:
/** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
会调用rangeCheckForAdd方法:
/** * A version of rangeCheck used by add and addAll. */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
所以执行add(int index, E element)方法时,当index大于ArrayList中已经包含的元素数时就会报ndexOutOfBoundsException。
当我们new ArrayList()时,默认给个空的数组,并未指定大小的数组。添加元素成功后会执行size++,删除元素成功会执行size--,size是元素个数,并不是数组的长度。
举报