package java.util;
/**
* 此类提供Collection接口的抽象实现,减小实现Collection接口的工作。
*
* 实现一个不可修改的collection,程序员只需要继承本类,并实现iterator和size方法。
* 实现一个可修改的collection,需要额外重写add和iterator接口的remove方法。
* @see Collection
* @since 1.2
*/
public abstract class AbstractCollection<E> implements Collection<E> {
protected AbstractCollection() {
}
// Query Operations
/**
* 继承于Collection,抽象待实现
*/
public abstract Iterator<E> iterator();
/**
* 继承于Collection,抽象待实现
*/
public abstract int size();
public boolean isEmpty() {
return size() == 0;
}
/**
* 利用Iterator遍历collection,直到找到目标元素则返回true,否则false
* 时间复杂度至少O(n)
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public boolean contains(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return true;
} else {
while (it.hasNext())
if (o.equals(it.next()))
return true;
}
return false;
}
/**
* 创建size长度的数组,使用Iterator遍历,将元素按照遍历顺序拷贝到数组中。
* 根据Iterator的实现,迭代器的长度可能等于或大于或小于size();
* 等于直接返回,小于使用Arrays.copyOf截断,大于调用finishToArray(r, it)
*/
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;
}
/**
* 见实测
* @throws ArrayStoreException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
@SuppressWarnings("unchecked")
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) {
r[i] = null; // null-terminate
} else if (a.length < i) {
return Arrays.copyOf(r, i);
} else {
System.arraycopy(r, 0, a, 0, i);
if (a.length > i) {
a[i] = null;
}
}
return a;
}
r[i] = (T)it.next();
}
// more elements than expected
return it.hasNext() ? finishToArray(r, it) : r;
}
/**
* 数组最大长度,超过这个值可能报OOM
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 当迭代器长度大于数组长度时调用。根据入参数据,新建一个长度1.5倍的数组。
* 如果超过数组的最大长度,则取数组最大长度。
* 最后对数据进行截断,截断为迭代器的最大长度。
*/
@SuppressWarnings("unchecked")
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 + (cap >> 1) + 1;
// overflow-conscious code
if (newCap - MAX_ARRAY_SIZE > 0)
newCap = hugeCapacity(cap + 1);
r = Arrays.copyOf(r, newCap);
}
r[i++] = (T)it.next();
}
// trim if overallocated
return (i == r.length) ? r : Arrays.copyOf(r, i);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError
("Required array size too large");
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
// Modification Operations
/**
* 在List顺序最后一位添加元素
* @throws UnsupportedOperationException
* @throws ClassCastException
* @throws NullPointerException
* @throws IllegalArgumentException
* @throws IllegalStateException
*/
public boolean add(E e) {
throw new UnsupportedOperationException();
}
/**
* 用Iterator遍历List,查找到入参o后,调用iterator.remove()删除元素。
* 需要注意考虑null元素。
* @throws UnsupportedOperationException
* @throws ClassCastException
* @throws NullPointerException
*/
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}
// Bulk Operations
/**
* 遍历入参collection,逐个元素调用contains()函数。
* @throws ClassCastException
* @throws NullPointerException
* @see #contains(Object)
*/
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
/**
* 遍历入参collection,循环调用 add()方法。
* 需注意只有一个元素添加成功,且后续不报错则为true
* @throws UnsupportedOperationException
* @throws ClassCastException
* @throws NullPointerException
* @throws IllegalArgumentException
* @throws IllegalStateException
*
* @see #add(Object)
*/
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
/**
* collection c 不能为null。
* 若c内的元素this里不包含,则无需移除。如果存在则调用remove。
* @throws UnsupportedOperationException
* @throws ClassCastException
* @throws NullPointerException
*
* @see #remove(Object)
* @see #contains(Object)
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
/**
* 遍历this的所有元素,如果入参集合里不包含该元素,则删除。
* @throws UnsupportedOperationException
* @throws ClassCastException
* @throws NullPointerException
*
* @see #remove(Object)
* @see #contains(Object)
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
/**
* 迭代遍历,调用remove()
* @throws UnsupportedOperationException {@inheritDoc}
*/
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
// String conversion
/**
* 遍历集合,将元素添加进StringBuilder
* @return a string representation of this collection
*/
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
}
源码学习之AbstractCollection
最新推荐文章于 2020-11-28 19:51:45 发布