Collection接口、List接口及迭代器

来源:互联网 发布:js手机端上传图片 编辑:程序博客网 时间:2024/06/08 14:37

在java类库中,集合的概念在Collection接口中得到抽象。


Collection接口中的一些方法

public interface MyCollection<T> extends MyIterator<T>{int size();boolean isEmpty();void clear();boolean contains(T element);boolean add(T element);boolean remove(T element);MyIterator<T> myIterator();}

在Collection接口中有一个获取迭代器的方法,用于获取迭代器,迭代器中的方法有

public interface MyIterator<T> {boolean hasNext();T next();void remove();}
在这里我们看到在MyCollection接口和MyIterator接口中都有remove方法,他们的主要区别在于

1、Collection的remove方法必须首先找出要被删除的项,如果知道所要删除的项的准确位置,则使用Collection中的remove方法删除开销较小。而迭代器的remove方法是删除由next方法最新返回的项。

2、在使用Iterator(而不是通过增强for循环间接使用)时:如果对正在被迭代的集合进行结构上的改变(即对集合进行add,remove或clear方法)时,那么迭代器就不再合法(抛出ConcurrentModificationException)


List接口实现Collection接口,其主要方法有:

public interface MyList<T> extends MyCollection<T> {T get(int index);T set(int index,T element);void add(int index,T element);void remove(int index,T element);MyListIterator<T> myListIterator();}

其中有获取迭代器的方法,其迭代器中所含有的方法有:

public interface MyListIterator<T> extends MyIterator<T>{boolean hasPrevious();T previous();void add(T element);void set(T element);}




0 0
原创粉丝点击