java中iterator迭代器的使用

package com.zhang.collection;


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

public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col=new ArrayList<>();
        col.add(new Book("1","11",111));
        col.add(new Book("2","22",222));
        col.add(new Book("3","33",333));
        System.out.println(col);
        Iterator iterator = col.iterator();
        while (iterator.hasNext()){//必须判断
            Object obj = iterator.next();
            System.out.println(obj);
        }
        //当iterator指针运行到最后时,再使用iterator.next会报错:NoSuchElementException

        //iterator.next();
        //快捷键,快速生成while循环=》itit
        //重置迭代器,把指针重新从最后面移动到最前面,不需要重新创建一个新的对象
        iterator = col.iterator();
        

    }
}
class Book{
    private String name;
    private String author;
    private int price;

    public Book(String name, String author, int 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 int getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

补充知识点:快速生成while循环遍历迭代器对象遍历iterator的快捷键是:itit

你可能感兴趣的:(java,迭代器模式)