这段代码是一个抽象类 MyAbstractCollection,它实现了 MyCollection 接口,并提供了一些基本的集合操作方法。
主要思想是定义了一些基本的集合方法,并提供了默认的实现。其中包括:
- size():返回集合中元素的数量;
- isEmpty():判断集合是否为空;
- contains(Object o):判断集合中是否包含指定元素;
- iterator():返回一个迭代器来遍历集合中的元素;
- add(Object e):向集合中添加元素(在这里默认会抛出 UnsupportedOperationException 异常);
- remove(Object o):从集合中删除指定元素;
- removeAll():删除集合中的所有元素;
- clear():清空集合中的元素。
这段代码的目的是定义一个抽象类,提供了一些通用的集合操作方法的默认实现,具体的集合类可以继承该抽象类并根据自己的需求去实现这些方法。
import java.util.Arrays;
import java.util.Iterator;
public abstract class MyAbastractCollection implements MyCollection{
@Override
public abstract int size();
@Override
public boolean isEmpty() {
return size()==0;
}
@Override
public abstract boolean contains(Object o);
public abstract Iterator<Object> iterator();
@Override
public boolean add(Object e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
Iterator<Object> 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;
}
@Override
public boolean removeAll() {
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
modified = true;
}
return modified;
}
@Override
public void clear() {
Iterator<Object> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
}