3.1、ArrayList
简介:
底层是可改变大小的数组结构,实现了list接口,线程不安全,可以加入null元素,元素有序,允许重复。适合查找,不适合指定位置的插入(adding n elements requires O(n) time)、删除操作。
UML图:
重要属性
/**
* 默认初始容量.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 最大可以分配的数组大小.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
复制代码
3.1.1添加元素
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
//扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
复制代码
3.1.2删除元素
/**
* 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;
return oldValue;
}
复制代码
3.1.3获取指定位置的元素
/**
* 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);
}
复制代码
3.1.4获取某个元素第一次出现的索引位置
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
复制代码
3.1.5获取某个元素最后一次出现的索引位置
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
复制代码
3.1.6更新某个索引位置的元素
/**
* 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;
}
复制代码
3.1.7扩容
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//新大小=原大小+原大小*0.5,即扩容到原来的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
复制代码
3.1.8返回数组大小
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
复制代码
3.1.9数组是否为空判断
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
复制代码
3.1.10是否包含某个元素
/**
* 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;
}
复制代码
3.1.11清空数组
/**
* 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;
}
复制代码
3.1.12交集操作
/**
* Retains only the elements in this list that are contained in the
* specified collection (optional operation). In other words, removes
* from this list all of its elements that are not contained in the
* specified collection.
*
* @param c collection containing elements to be retained in this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean retainAll(Collection<?> c);
复制代码
3.1.13添加某个集合的所有元素
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator (optional operation). The behavior of this
* operation is undefined if the specified collection is modified while
* the operation is in progress. (Note that this will occur if the
* specified collection is this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this list
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this list
* @see #add(Object)
*/
boolean addAll(Collection<? extends E> c);
复制代码
3.1.13删除数组中所有在特定集合中出现的元素
/**
* Removes from this list all of its elements that are contained in the
* specified collection (optional operation).
*
* @param c collection containing elements to be removed from this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean removeAll(Collection<?> c);
复制代码
示例:
public class ArrayListTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(null);
list.add(1);
list.add(2);
System.out.println(list);
System.out.println("list 第一次出现元素的索引值:" + list.indexOf(1));
System.out.println("list 最后一次出现元素的索引值:" + list.lastIndexOf(1));
list.set(1, 6);
System.out.println(list);
System.out.println("list 是否为空?" + list.isEmpty());
System.out.println("list 是否包含元素6?" + list.contains(6));
list.clear();
System.out.println("list 大小:" + list.size());
//Arrays 中的 ArrayList 与 util 包下的 ArrayList 不同,要进行转换
List<Integer> temp2 = Arrays.asList(1, 2, 3);
List<Integer> temp3 = Arrays.asList(2, 3, 4);
List<Integer> list2 = new ArrayList<>(temp2);
List<Integer> list3 = new ArrayList<>(temp3);
list.addAll(list2);
list.addAll(list3);
System.out.println(list);
list2.retainAll(list3);
System.out.println("list2 与list3 的交集:" + list2);
list.removeAll(list2);
System.out.println("list3 与 list2 的差集:" + list);
list.addAll(list2);
System.out.println("list3 与 list2 的并集:" + list);
}
}
复制代码
运行结果:
[1, null, 1, 2]
list 第一次出现元素的索引值:0
list 最后一次出现元素的索引值:2
[1, 6, 1, 2]
list 是否为空?false
list 是否包含元素6?true
list 大小:0
[1, 2, 3, 2, 3, 4]
list2 与list3 的交集:[2, 3]
list3 与 list2 的差集:[1, 4]
list3 与 list2 的并集:[1, 4, 2, 3]复制代码