Collection遍历集合Iterator迭代器

package com.collection_;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
    1. Iterator 对象称为迭代器,主要用于遍历Collection集合中的元素
    2. 所有实现了Collection接口的集合类都有一个iteration()方法,用以
    返回一个Iterator接口的对象,即可以返回一个迭代器
    3. Iterator仅用于遍历集合,Iterator本身并不存在对象
 */
public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {

        Collection col = new ArrayList();
        col.add(new Book("三国演义","罗贯中",10.1));
        col.add(new Book("小李飞刀","古龙",5.1));
        col.add(new Book("红楼梦","曹雪芹",34.6));

        //System.out.println("col=" + col);
        //遍历 col 集合
        //1. 先得到 col 对应的迭代器
        Iterator iterator = col.iterator();
        //2. 使用while循环遍历
//        while (iterator.hasNext()) {//判断是否还有下一个数据
//            //返回下一个元素,类型是Object
//            Object obj = iterator.next();//用next()方法获取数据
//            System.out.println("obj=" + obj);
//        }
        //快捷键,快速生成  itit
        //显示所有快捷键的快捷键 ctrl + j
        while (iterator.hasNext()) {
            Object obj =  iterator.next();
            System.out.println("obj=" + obj);
        }
        //3. 当退出while循环后,只是iterator迭代器,指向了最后一个数据
        //iterator.next();//NoSuchElementException异常
        //4. 如果希望再次遍历,需要重置iterator
        iterator = col.iterator();
        System.out.println("======第二次遍历=========");
        while (iterator.hasNext()) {
            Object obj =  iterator.next();
            System.out.println("obj=" + obj);

        }

    }
}

class Book{
    private String name;
    private String author;
    private double price;

    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、付费专栏及课程。

余额充值