java List.add操作可以指定位置,addAll也可以指定;
使用:
public class Test02 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("str1"); list.add("str2"); list.add(1,"str222"); for (int i = 0; i < list.size(); i++) { CusPrint.print(list.get(i)); } } }
方法源码:
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++; }
注意对index做了判断;
private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }