在Java编程语言中,集合框架是其核心组成部分之一,它为Java程序员提供了一套丰富的接口和实现,用于存储、检索、排序和搜索对象。本文将深入剖析Java集合框架的源码,从入门到精通,旨在帮助读者全面理解集合框架的工作原理,以及如何高效地进行数据处理。
前言
Java集合框架主要包括以下接口和类:
- Collection接口:它是所有集合类的根接口,定义了集合共有的操作。
- List接口:继承自Collection接口,表示有序集合,元素可以重复。
- Set接口:继承自Collection接口,表示无序集合,元素不可重复。
- Map接口:与Collection接口并列,表示键值对集合。
- Queue接口:继承自Collection接口,表示元素先进先出(FIFO)的集合。
- Deque接口:继承自Queue接口,表示双端队列,元素可以添加到两端。
Java集合框架提供了多种实现,如ArrayList、LinkedList、HashSet、HashMap等,每种实现都有其独特的性能特点和适用场景。
入门篇:集合框架概述
集合框架的组成
Java集合框架由接口、抽象类和具体实现类组成。接口定义了集合的操作规范,抽象类提供了部分操作的实现,具体实现类则实现了接口中的所有方法。
集合框架的分类
根据存储元素的方式和特性,集合框架可以分为以下几类:
- List:有序集合,元素可以重复,如ArrayList、LinkedList。
- Set:无序集合,元素不可重复,如HashSet、TreeSet。
- Map:键值对集合,如HashMap、TreeMap。
- Queue:先进先出(FIFO)的集合,如ArrayDeque、PriorityQueue。
- Deque:双端队列,元素可以添加到两端,如ArrayDeque、LinkedList。
深入篇:常用集合类的源码剖析
ArrayList
ArrayList是List接口的一个实现类,基于动态数组实现。以下是ArrayList的几个关键点:
- 数据结构:内部使用Object数组存储元素。
- 扩容策略:当数组容量不足时,会自动扩容,扩容策略为原容量的1.5倍。
- 遍历方式:通过索引遍历或使用迭代器遍历。
”`java
public class ArrayList
private static final long serialVersionUID = 8683452581122892189L;
private static final int DEFAULT_CAPACITY = 10;
private transient Object[] elementData;
private int size;
public ArrayList() {
this.elementData = DEFAULT_CAPACITY;
}
public ArrayList(int initialCapacity) {
if (initialCapacity >= 0) {
this.elementData = new Object[initialCapacity];
} else {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
if (o == null) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return true;
}
}
}
return false;
}
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;
}
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;
}
public E get(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return (E) elementData[index];
}
public E set(int index, E element) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
public void add(int index, E element) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
public E remove(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return oldValue;
}
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;
}
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;
}
public void add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
}
public void clear() {
modCount++;
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = elementData.clone();
return v;
} catch (CloneNotSupportedException e) {
// This should never happen, since we are Cloneable
throw new InternalError(e);
}
}
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
modCount++;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++) {
if (!c.contains(elementData[r])) {
if (w != r) {
elementData[w] = elementData[r];
}
w++;
} else {
modified = true;
}
}
if (modified) {
size = w;
}
} finally {
if (r != size) {
System.arraycopy(elementData, w, elementData, 0, r - w);
modCount++;
}
}
return modified;
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
modCount++;
int r = 0;
boolean modified = false;
try {
for (; r < size; r++) {
if (c.contains(elementData[r])) {
if (r != w) {
elementData[w] = elementData[r];
}
w++;
} else {
modified = true;
}
}
if (modified) {
size = w;
}
} finally {
if (r != size) {
System.arraycopy(elementData, w, elementData, 0, r - w);
modCount++;
}
}
return modified;
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new ArrayList<>(this, fromIndex, toIndex);
}
private void ensureCapacityInternal(int minCapacity) {
if (minCapacity - elementData.length > 0) {
grow(minCapacity);
}
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
if (newCapacity - MAX_ARRAY_SIZE > 0) {
newCapacity = hugeCapacity(minCapacity);
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) {
throw new OutOfMemoryError();
}
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(elementData.length);
for (int i = 0; i < size; i++) {
s.writeObject(elementData[i]);
}
}
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
int capacity = s.readInt();
ensureCapacityInternal(capacity);
Object[] a = new Object[capacity];
int i = 0;
while (i < size) {
a[i] = s.readObject();
i++;
}
elementData = a;
}
private void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0 || toIndex > size) {
throw new IndexOutOfBoundsException();
}
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
}
private void rangeCheck(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last returned element
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
E x = (E) elementData[i];
cursor = i + 1;
lastRet = i;
return x;
}
public void remove() {
checkForComodification();
int lastRet = this.lastRet;
if (lastRet == -1)
throw new IllegalStateException();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index);
return new Itr(index);
}
public ListIterator<E> listIterator() {
return new Itr(0);
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(elementData[i]);
if (i < size - 1)
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
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;
}
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;
}
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
System.arraycopy(elementData, index, elementData, index + numNew, size - index);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
public E set(int index, E element) {
if (index >= size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
public E remove(int index) {
if (index >= size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return oldValue;
}
public boolean containsAll(Collection<?> c) {
Objects.requireNonNull(c);
for (Object e : c) {
if (!contains(e))
return false;
}
return true;
}
public boolean addAll(Collection<? extends E> c) {
Objects.requireNonNull(c);
return c.isEmpty() ? false : addAll(size, c);
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return c.isEmpty() ? false : modifiedRemoveAllFromTo(0, size, c);
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return c.isEmpty() ? false : modifiedRemoveAllFromTo(0, size, c);
}
private boolean modifiedRemoveAllFromTo(int fromIndex, int toIndex, Collection<?> c) {
if (c.isEmpty())
return false;
modCount++;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < toIndex; r++) {
if (!c.contains(elementData[r])) {
if (r != w) {
elementData[w] = elementData[r];
}
w++;
} else {
modified = true;
}
}
if (modified) {
size = w;
}
} finally {
if (r != size) {
System.arraycopy(elementData, w, elementData, 0, r - w);
modCount++;
}
}
return modified;
}
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (elementData.length == CAPACITY) ? elementData : Arrays.copyOf(elementData, size);
}
}
public void ensureCapacity(int minCapacity) {
modCount++;
if (minCapacity > elementData.length) {
grow(minCapacity);
}
}
public int hashCode() {
int h = 0;
int i = 0;
final Object[] elementData = this.elementData;
final int size = this.size;
for (; i < size; i++) {
h ^= elementData[i].hashCode() & 0x7fffffff;
}
return h ^ (size >>> 32);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
List<?> that = (List<?>)
