AbstractCollection<E> implements Collection<E>

AbstractCollection 最小化实现Collection接口,需要自己实现iterator和size接口

  

  public abstract Iterator<E> iterator();

   public abstract int size();

 

public boolean isEmpty() {
        return size() == 0;
}

public boolean contains(Object o) {  集合是否有某一个元素,利用迭代器遍历集合,有就返回true。
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 Object[] toArray();
public <T> T[] toArray(T[] a);   返回一个包含集合所有元素的数组,(这个数组是新创建的数组)并会保持集合原有顺序

public boolean add(E e) {  添加一个元素,子类实现
throw new UnsupportedOperationException();
}

public boolean remove(Object o) {  使用子类实现的迭代器的remove
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 boolean containsAll(Collection<?> c) {  判断集合中是否包含一个特定集合的所有元素
for (Object e : c)
if (!contains(e))
return false;
return true;
}

public boolean addAll(Collection<? extends E> c) {}  
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;
}

public boolean retainAll(Collection<?> c) { 与removeAll 判断逻辑相反,只要不包含在另外一个集合中,就移除
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}

public void clear() { 移除集合中的所有元素
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
 

 

posted @ 2023-02-17 10:57  小小小小青石  阅读(27)  评论(0)    收藏  举报