迭代器遍历

显示IDEA中所有快捷键 ctrl+j
 

 

 

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName CollectionIterator.java
 * @Description TODO
 * @createTime 2021年09月10日 16:03:00
 */
public class CollectionIterator {
    public static void main(String[] args) {
        Collection<Object> col = new ArrayList<>();
        col.add(new book("三国演义","张三",10.2));
        col.add(new book("红楼","张四",12.2));
        col.add(new book("六神演义","张五",5.2));
        col.add("jackie");
        System.out.println("col="+col);
        //1.先得到col对应的迭代器
        Iterator<Object> iterator = col.iterator();

        //2.使用while循环遍历
        //此处有快捷键生成while循环,itit
        //显示所有快捷键 ctrl+j
        while(iterator.hasNext()){
            //返回下一个元素,类型是Object
            Object o = iterator.next();
            System.out.println(o);
        }

        //3.当退出循环后这时迭代器指向最后一个元素
        //itretaor.next();//会抛出异常NOSuchElementException

        //4.如果想再次遍历,重置
        iterator=col.iterator();
        System.out.println("第二次遍历");
        while (iterator.hasNext()) {
            Object next =  iterator.next();

        }
    }
}
class book{
    private String name;
    private String author;
    private double price;

    public book() {
    }

    public book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值