Collection与Iterator的关系

在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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值