今天无意间看到List源码中得remove(int index)方法,先上源码:
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
大家看一下源码 主要看一下返回值,是删除的那个元素,所以以后当我然们需要获得List中的某一个元素,然后然后删除的时候不需要执行两部操作,只要一步操作就行了,原来写法经常是
View view=List.get(0);
List.remove(0);
return view;
而现在return list.remove(index),这样一举两得,代码瞬间很简洁了