---
title: "Java集合2：类 AbstractCollection及源码"
author: "xuxujing"
date: "2013-03-19T10:52:24Z"
tags: []
categories: ["编程语言"]
slug: "java-2-abstractcollection"
draft: false
lastmod: "2013-03-19T13:56:59Z"
id: 1831662
url: "https://xujava.iteye.com/blog/1831662"
---

**1.继承关系图**

![](http://dl.iteye.com/upload/attachment/0081/8586/6ad6c830-d829-3827-9cd1-de6f40067b67.png)  
   
 

**2. 概览**

此类提供 `Collection` 接口的骨干实现，以最大限度地减少了实现此接口所需的工作。

![](http://dl.iteye.com/upload/attachment/0081/8582/8561a52c-14d0-3510-9b51-f662d4a0460c.png)  
**3.方法**

**构造方法摘要** `protected` `AbstractCollection()`   
          唯一的构造方法。

 

**方法摘要** `boolean` `add(E e)`   
          确保此 collection 包含指定的元素（可选操作）。 `boolean` `addAll(Collection<? extends E> c)`   
          将指定 collection 中的所有元素都添加到此 collection 中（可选操作）。 `void` `clear()`   
          移除此 collection 中的所有元素（可选操作）。 `boolean` `contains(Object o)`   
          如果此 collection 包含指定的元素，则返回 `true`。 `boolean` `containsAll(Collection<?> c)`   
          如果此 collection 包含指定 collection 中的所有元素，则返回 `true`。 `boolean` `isEmpty()`   
          如果此 collection 不包含元素，则返回 `true`。 `abstract  Iterator<E>` `iterator()`   
          返回在此 collection 中的元素上进行迭代的迭代器。 `boolean` `remove(Object o)`   
          从此 collection 中移除指定元素的单个实例，如果存在的话（可选操作）。 `boolean` `removeAll(Collection<?> c)`   
          移除此 collection 中那些也包含在指定 collection 中的所有元素（可选操作）。 `boolean` `retainAll(Collection<?> c)`   
          仅保留此 collection 中那些也包含在指定 collection 的元素（可选操作）。 `abstract  int` `size()`   
          返回此 collection 中的元素数。 `Object[]` `toArray()`   
          返回包含此 collection 中所有元素的数组。

`<T> T[]`

`toArray(T[] a)`   
          返回包含此 collection 中所有元素的数组；返回数组的运行时类型与指定数组的运行时类型相同。 `String` `toString()`   
          返回此 collection 的字符串表示形式。

 

**4.添加元素相关方法源码**

 

```
	// 确保此 collection 包含指定的元素
	public boolean add(E e) {
		throw new UnsupportedOperationException();
	}

	// 将指定 collection 中的所有元素都添加到此 collection 中
	public boolean addAll(Collection<? extends E> c) {
		boolean modified = false;
		Iterator<? extends E> e = c.iterator();
		while (e.hasNext()) {
			if (add(e.next()))
				modified = true;
		}
		return modified;
	}
```

 

 

**5.移除元素相关方法源码**

 

```
	// 从此 collection 中移除指定元素的单个实例，如果存在的话
	public boolean remove(Object o) {
		Iterator<E> e = iterator();
		if (o == null) {
			while (e.hasNext()) {
				if (e.next() == null) {
					e.remove();
					return true;
				}
			}
		} else {
			while (e.hasNext()) {
				if (o.equals(e.next())) {
					e.remove();
					return true;
				}
			}
		}
		return false;
	}

	// 移除此 collection 中那些也包含在指定 collection 中的所有元素
	public boolean removeAll(Collection<?> c) {
		boolean modified = false;
		Iterator<?> e = iterator();
		while (e.hasNext()) {
			if (c.contains(e.next())) {
				e.remove();
				modified = true;
			}
		}
		return modified;
	}

	// 仅保留此 collection 中那些也包含在指定 collection 的元素
	public boolean retainAll(Collection<?> c) {
		boolean modified = false;
		Iterator<E> e = iterator();
		while (e.hasNext()) {
			if (!c.contains(e.next())) {
				e.remove();
				modified = true;
			}
		}
		return modified;
	}

	// 移除此 collection 中的所有元素
	public void clear() {
		Iterator<E> e = iterator();
		while (e.hasNext()) {
			e.next();
			e.remove();
		}
	}
```

 

 

**6.查找相关方法源代码**

 

```
	// 如果此 collection 包含指定的元素，则返回 true
	public boolean contains(Object o) {
		Iterator<E> e = iterator();
		if (o == null) {
			while (e.hasNext())
				if (e.next() == null)
					return true;
		} else {
			while (e.hasNext())
				if (o.equals(e.next()))
					return true;
		}
		return false;
	}

	// 如果此 collection 包含指定 collection 中的所有元素，则返回 true
	public boolean containsAll(Collection<?> c) {
		Iterator<?> e = c.iterator();
		while (e.hasNext())
			if (!contains(e.next()))
				return false;
		return true;
	}

	// 返回此 collection 中的元素数
	public abstract int size();

	// 如果此 collection 不包含元素，则返回 true
	public boolean isEmpty() {
		return size() == 0;
	}
```

 

 

**7.转换相关方法源代码**

 

```
	// 返回在此 collection 中的元素上进行迭代的迭代器
	public abstract Iterator<E> iterator();

	// 返回包含此 collection 中所有元素的数组
	public Object[] toArray() {
		// Estimate size of array; be prepared to see more or fewer elements
		Object[] r = new Object[size()];
		Iterator<E> it = iterator();
		for (int i = 0; i < r.length; i++) {
			if (!it.hasNext()) // fewer elements than expected
				return Arrays.copyOf(r, i);
			r[i] = it.next();
		}
		return it.hasNext() ? finishToArray(r, it) : r;
	}

	// 返回包含此 collection 中所有元素的数组；返回数组的运行时类型与指定数组的运行时类型相同
	public <T> T[] toArray(T[] a) {
		// Estimate size of array; be prepared to see more or fewer elements
		int size = size();
		T[] r = a.length >= size ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
		Iterator<E> it = iterator();

		for (int i = 0; i < r.length; i++) {
			if (!it.hasNext()) { // fewer elements than expected
				if (a != r)
					return Arrays.copyOf(r, i);
				r[i] = null; // null-terminate
				return r;
			}
			r[i] = (T) it.next();
		}
		return it.hasNext() ? finishToArray(r, it) : r;
	}

	//
	private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
		int i = r.length;
		while (it.hasNext()) {
			int cap = r.length;
			if (i == cap) {
				int newCap = ((cap / 2) + 1) * 3;
				if (newCap <= cap) { // integer overflow
					if (cap == Integer.MAX_VALUE)
						throw new OutOfMemoryError("Required array size too large");
					newCap = Integer.MAX_VALUE;
				}
				r = Arrays.copyOf(r, newCap);
			}
			r[i++] = (T) it.next();
		}
		// trim if overallocated
		return (i == r.length) ? r : Arrays.copyOf(r, i);
	}

	// 返回此 collection 的字符串表示形式
	public String toString() {
		Iterator<E> i = iterator();
		if (!i.hasNext())
			return "[]";

		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (;;) {
			E e = i.next();
			sb.append(e == this ? "(this Collection)" : e);
			if (!i.hasNext())
				return sb.append(']').toString();
			sb.append(", ");
		}
	}
```