在C++中没有容器的公共基类,所有容器共性通过迭代器达成。
Java中新增了Collection,用来描述所有序列容器共性接口的根接口。而其实Collection与迭代器绑定,实现Collection就得提供iterator()方法(也就是继承Iterable接口)。
示例程序展现了三种表示以及操作容器的方式,可以看出Collection与Iterator是序列容器的共性。
class SimpleListIterator{
//方法一
public static void display(Iterator it){
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
}
//方法二
public static void display(Iterable col){
Iterator it=col.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
}
//方法三
public static void display(Collection col){
for(Object obj:col)
System.out.print(obj+" ");
System.out.println();
}
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>(Arrays.asList(1,2,3,4));
display(list);
display(list.iterator());
}
}
//output:
//1 2 3 4
//1 2 3 4
实现简单的Collection
虽然AbstractCollection是Collection的实现,但被强制实现iterator()和size()方法,因为这和我们自己如何设置容器底层有关。
程序中的remove作为可选操(也可以不写)作未支持,只是抛出异常。
class MyCollection extends AbstractCollection{
private Integer[] ints=new Integer[]{
1,2,3,4
};
public int size=ints.length;
public int size() { return size; }
public Iterator iterator() {
return new Iterator<Integer>() {
private int index=0;
public boolean hasNext() {
return index<size;
}
public Integer next() {
return ints[index++];
}
public void remove(){
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
MyCollection myCollection=new MyCollection();
System.out.println(myCollection);
}
}
//output:
//[1, 2, 3, 4]