标签:hose erro out poi 遍历数组 api 简单 sel move
目录
正文
如果此列表中没有元素,则返回 true
/**
* Returns <tt>true</tt> if this list contains no elements.*/
public boolean isEmpty() {
return size == 0;
}
判断ArrayList是否为空,size为0时,即不包含任何成员时为空,返回true。
返回此列表中首次出现的指定元素的索引,或如果此列表不包含元素,则返回 -1。
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
原理就是从前向后遍历数组,看其中是否有元素与所给的元素相等,有则返回索引。
返回此列表中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回 -1。
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
此方法原理同IndexOf,只是从后向前遍历。
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
contains方法中调用indexOf方法,如果ArrayList中含有此元素,则IndexOf返回的索引值一定大于等于零。
返回此 ArrayList 实例的浅表副本。
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn‘t happen, since we are Cloneable
throw new InternalError(e);
}
}
clone方法先调用根类Object的clone方法复制一个ArrayList v,然后将当前ArrayList的elementData复制到一个新数组,并让ArrayList v的elementData指向新数组。
因为v是新建立的,没有被修改过,modCount赋值为0。
注意,clone只是对ArrayList的浅复制,成员本身并没有被复制。
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
toArray()方法返回一个包含ArrayList所有元素的数组。该方法其实分配了一个新的Object数组,将elementData的成员复制到新的Object数组中,并将这个数组返回。
注意,ArrayList中没有指向toArray返回的数组的引用,调用者可以随意修改。
toArray方法充当着基于Array和基于Collection的APIs的桥梁。
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
/**
* Returns an array containing all of the elements in this list in proper
* sequence (from first to last element); the runtime type of the returned
* array is that of the specified array. If the list fits in the
* specified array, it is returned therein. Otherwise, a new array is
* allocated with the runtime type of the specified array and the size of
* this list.
*
* <p>If the list fits in the specified array with room to spare
* (i.e., the array has more elements than the list), the element in
* the array immediately following the end of the collection is set to
* <tt>null</tt>. (This is useful in determining the length of the
* list <i>only</i> if the caller knows that the list does not contain
* any null elements.)
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a‘s runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
这个方法是将ArrayList的所有元素拷贝到数组a中。
当ArrayList的size大于a的length时,也就是说a太小容纳不下ArrayList的所有元素,则调用Arrays.copyOf进行复制,这时不会再使用a,而是新开一个数组足够大的数组,将元素复制到新数组后将新数组返回。
如果a足够大可以容纳ArrayList的所有元素时,调用System.arraycopy进行复制,a的前size个位置是从ArrayList复制过来的元素,如果a.size==ArrayList.length,恰好装满,直接返回;如果a.size>ArrayList.length,则a[size]=null,表示结束。
// Positional Access Operations
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
elementData方法返回其内部数组elementData的index位置上的元素。供get(int index)方法调用。
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
rangeCheck方法其实就是检测index是否越界,ArrayList只有size个元素,index>=size时抛出越界异常。
rangeCheckForAdd()方法也是检测index是否越界,条件是index<0 || index >size。
值得注意的一点是rangeCheck和rangeCheckForAdd方法检测越界的提条件的差别:
rangeCheck供get、set和remove方法调用,这些都是在已经存在的元素上操作,范围自然是0到size-1;
rangeCheckForAdd方法由add方法调用,添加元素的位置可以是0到size-1,表示在元素中间插入,也可以是size,表示在所有元素之后插入。但是在大于size的位置插入时不可以,因为插入的元素和原有元素之间就留下了空档。
返回此列表中指定位置上的元素。
/**
* 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) {
rangeCheck(index);
return elementData(index);
}
用指定的元素替代此列表中指定位置上的元素。
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
移除此列表中指定位置上的元素
/**
* 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;
}
值得注意的是,当移除某个元素之后,它之后的所有元素都要向前移动一位,计算方式为 numMoved=size-index-1;
当index为size-1时,没有需要移动的元素;
numMoved>0时,调用System.arraycopy()方法移动元素,而且elementData[--size]=null,这里还将size减了1。
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
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
}
fastRemove方法是私有的,仅供remove(Object o)方法调用。
fastRemove方法和remove(int index)方法的不同之处只在于fastRemove不进行边界检查,不返回值;因为fastRemove不需要这些功能。
移除此列表中首次出现的指定元素(如果存在)。
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
方法移除ArrayList中出现的第一个元素o,采用遍历的方式获得要删除元素的索引index,然后调用fastRemove(int index)将其移除。
注意对元素o的判等方式,为null时使用==,否则使用equals方法。
移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。
/**
* Removes from this list all of the elements whose index is between
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
* Shifts any succeeding elements to the left (reduces their index).
* This call shortens the list by {@code (toIndex - fromIndex)} elements.
* (If {@code toIndex==fromIndex}, this operation has no effect.)
*
* @throws IndexOutOfBoundsException if {@code fromIndex} or
* {@code toIndex} is out of range
* ({@code fromIndex < 0 ||
* fromIndex >= size() ||
* toIndex > size() ||
* toIndex < fromIndex})
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
removeRange(int fromIndex, int toIndex)方法是移除list中fromIndex到toIndex之间的元素,注意包括fromIndex,但是不包括toIndex;
还要注意,fromIndex的合法取值为0到size-1,toIndex的合法取值为0到size,而且toIndex≥fromIndex;
当fromIndex==toIndex时, 此函数不做任何操作。
当移除n个元素之后,这之后的所有元素都要向前移动n位,计算方式为 numMoved=size-toIndex;
当toIndex为size时,没有需要移动的元素;
numMoved>0时,调用System.arraycopy()方法移动元素。
List的size变为newSize = size - (toIndex-fromIndex),并且elementData从newSize到size-1都要填充为null,最后size=newSize。
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
此方法只是用来辅助在发生异常时输出越界信息的。
移除此列表中的所有元素。
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
clear方法比较简单,将所有的元素赋值为null即可。
前者移除ArrayList中那些也包含在指定 collection 中的所有元素(可选操作)。此调用返回后,collection 中将不包含任何与指定 collection 相同的元素。
后者仅保留ArrayList中那些也包含在指定 collection 的元素(可选操作)。换句话说,移除此 collection 中未包含在指定 collection 中的所有元素。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
这两个方法都是调用batchRemove实现:
batchRemove(c,false);
batchRemove(c,true);
不同的地方只有第二个参数一个为false,一个为true。
实现移除或保留ArrayList中那些也包含在指定 collection 中的所有元素。
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
这个方法的重点在下面几句:
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
当complement为true时,elementData中所有包含在c中的元素被保留了下来;
当complement为false时,elementData中所有未包含在c中的元素被保留了下来。
标签:hose erro out poi 遍历数组 api 简单 sel move
原文地址:http://www.cnblogs.com/zhangyuhang3/p/6909953.html