Java迭代器

迭代器

迭代器使用时的注意点

1、不能在前面加’*'来得到实例
2、直接打印迭代器意义不大
3、只能通过next(双向迭代器还有previous)方法来得到实例
4、实现了迭代器的类可以用foreach语法

默认迭代器的定向元素注意点(以双向迭代器为例)

it为迭代器,数字为迭代器索引

在这里插入图片描述

自己实现迭代器(以单向迭代器为例)

    package Test;
    import java.util.*;
    class MyList<T> implements Iterable<T> {
    static final private int DEFAULT_LENGTH = 100;
    private int NOW_LENGTH=100;
    private int end = 0;
    T[] list;

    //构造部分
    public MyList(int length) {
        list = (T[]) new Object[length];
    }

    public MyList() {
        this(DEFAULT_LENGTH);
    }

    //Iterator实现部分
    public Iterator<T> iterator() {
        class MyIterator implements Iterator {
            private int address = 0;

            public boolean hasNext() {
                return address != end;
            }

            public T next() {
                return list[address++];
            }
        }
        return new MyIterator();
    }

    //功能实现部分
    public void resize(int length){
        T[]temp = (T[]) new Object[length];
        System.arraycopy(list,0,temp,0,end);
        list=temp;
    }
    public void add(T obj) {
        list[end++] = obj;
        if(end==NOW_LENGTH)resize(NOW_LENGTH+10);
    }

    public T get(int index) {
        return list[index];
    }
    public int getSize(){
        return end;
    }
    public boolean contains(T obj) {
        for (T temp : this) {
            if (temp.equals(obj)) return true;
        }
        return false;
    }    //找到返回true,反之返回false

    public boolean remove(T obj) {
        for (int i = 0; i < end; i++) {
            if (list[i].equals(obj)) {
                for (int j = i + 1; j < end; j++) list[j - 1] = list[j];
                end--;
                return true;
            }
        }
        return false;
    }     //成功返回true,反之返回false

    public int indexOf(T obj) {
        int i = 0;
        for (T temp : this) {
            if (temp.equals(obj)) return i;
            i++;
        }
        return -1;
    } //找到就返回数组对应位置,反之返回-1

    public void print() {
        for (T temp : this) {
            System.out.print(temp.toString()+" ");
        }
        System.out.println();
    }
}
public class Test
{
    public static void main(String[] args)
    {
        //按Integer类型test
        MyList<Integer> list=new MyList<Integer>();
        Random rad=new Random();
        //随机初始化
        for(int i=0;i<15;i++)list.add(rad.nextInt(100));
        list.print();
        //随机移除一个元素
        list.remove(list.get(rad.nextInt(list.getSize())));
        //迭代器foreach打印
        Iterator<Integer> i=list.iterator();
        while(i.hasNext())System.out.print(i.next()+" ");
    }
}

依此实现,既可以生成该存储类的迭代器来循环遍历,也可以像print方法一样用foreach语法
自己实现迭代器时,其指向元素和迭代器索引将根据实现来决定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值