package resource.impl;
import resource.Collection;
import java.io.ObjectStreamConstants;
import java.util.Iterator;
public abstract class AbstractCollection<E> implements Collection<E> {
protected AbstractCollection() {
}
public abstract Iterator<E> iterator();
public abstract int size();
/**
* 判断是否为空
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* 判断是否包含
*/
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;
}
public boolean add(E e) {
throw new UnsupportedOperationException();
}
/**
* 移除元素
* */
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;
}
/**
* 清空集合
*/
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
/**
* 包含全部
*/
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
/**
* toString()
*/
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
最新推荐文章于 2021-12-04 11:44:50 发布