Iterater迭代器和增强for循环

1、Collection接口遍历元素---Iterator迭代器

看一下下面这张图片:可以看出Collection接口有一个父接口Iterable,Iterable接口有一个iterator()方法,iterator()方法的类型是Iterator迭代器,实际上当我们使用方法时,返回的是一个Iterator对象,目的是实现元素的遍历。

Iterator接口介绍

集合的迭代操作就是将集合中的元素逐个地遍历取出来。

  • iterator对象称为迭代器,主要用于遍历Collection集合中的元素。

  • 所有实现了Collection接口集合类都有一个iterator()方法,用以返回一个实现了iterator接口的对象,既可以返回一个迭代器。

  • Iterator仅用于遍历集合,Iterator本身并不存放对象。

Iterator接口的方法

Iterator接口的方法有hasNext()、next()、remove()。

注意:在调用iterator,next()方法之前必须要调用iterator.hasNext()进行检测。如不调用,且下一条记录无效,直接调用iterator.next()会抛出NoSuchElementWxception异常。

迭代器的执行原理

Iterator iterator= coll.iterator();//得到一个集合的迭代器

//hasNext():判断是否还有下一个元素

while(iterator.hasNext()){

//next()作用:1、下移。2、将下移以后集合位置上的元素返回

System.out.println(iterator.next());

}

原理实现

java 复制代码
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


public class IteratorUse {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        //由于接口不能直接被实例化,只有实现了接口的类才能被实例化,所以这里我们使用ArrayList
        //使用collection接口接收
        Collection collection = new ArrayList();
        //(1)普通输出
        collection.add(new Book("三国演义","罗贯中",100.4));
        collection.add(new Book("红楼梦","曹雪芹",87));
        collection.add(new Book("水浒传","施耐庵",80.4));
        //System.out.println(collection);
        //[B00k{name='三国演义', author='罗贯中', price=100.4},
        // B00k{name='红楼梦', author='曹雪芹', price=87.0},
        // B00k{name='水浒传', author='施耐庵', price=80.4}]

        //(2)使用迭代器
        Iterator iterator = collection.iterator();
        //先得到collection对应的迭代器,使用while遍历
        while(iterator.hasNext()){
            //返回下一个元素,类型是Object
            Object obj = iterator.next();
            System.out.println(obj);
            //B00k{name='三国演义', author='罗贯中', price=100.4}
            //B00k{name='红楼梦', author='曹雪芹', price=87.0}
            //B00k{name='水浒传', author='施耐庵', price=80.4}
        }

    }
}
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 "B00k{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

2、Collection接口遍历对象---for循环增强

增强for循环介绍

增强for循环,可以代替iterator迭代器。

特点:增强for就是简化版的iterator,本质一样。只能用于遍历集合或数组

基本语法:

for(元素类型 元素名 集合名或数组名){

访问元素;

}

案例演示:

集合中使用增强for循环:

java 复制代码
package com.lwtstu6.practice3;

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


public class IteratorUse {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {

        //由于接口不能直接被实例化,只有实现了接口的类才能被实例化,所以这里我们使用ArrayList
        //使用collection接口接收
        Collection collection = new ArrayList();
        //(1)普通输出
        collection.add(new Book("三国演义","罗贯中",100.4));
        collection.add(new Book("红楼梦","曹雪芹",87));
        collection.add(new Book("水浒传","施耐庵",80.4));
        //System.out.println(collection);
        //[B00k{name='三国演义', author='罗贯中', price=100.4},
        // B00k{name='红楼梦', author='曹雪芹', price=87.0},
        // B00k{name='水浒传', author='施耐庵', price=80.4}]

        
        //(2)使用增强for循环
        for(Object obj:collection){//把collection中的对象依次取出,并赋给obj,然后再输出obj
            System.out.println(obj);
        }
        //B00k{name='三国演义', author='罗贯中', price=100.4}
        //B00k{name='红楼梦', author='曹雪芹', price=87.0}
        //B00k{name='水浒传', author='施耐庵', price=80.4}

    }
}
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 "B00k{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

直接在数组中使用增强for循环:

int[] nums = {1,8,19,76};

for(int i:num){

System.out.println("i="+i);

}

//输出结果:

//1

//8

//19

//76

3、迭代器和增强for练习题

创建三个Dog{name,age}对象,放入到ArrayList中,赋给List引用,用迭代器和增强for循环两种方式来遍历,重写Dog的toString 方法,输出name和age.

java 复制代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Dog{
    private String name;
    private int age;
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class CollectionExercise {
    public static void main(String[] args) {
        //由于接口不能直接被实例化,只有实现了接口的类才能被实例化。
        //这里使用list来接收,是因为ArrayList的实现类也有List接口。
        //创建流浪猫集合
        List list = new ArrayList();
        //创建流浪猫对象
        Dog dog1 = new Dog("小花",3);
        Dog dog2 = new Dog("小白",4);
        Dog dog3 = new Dog("小黑",7);
        //把流浪猫放到集合中
        list.add(dog1);
        list.add(dog2);
        list.add(dog3);
        //方式一使用迭代器遍历数组输出数据
        Iterator iterator = list.iterator();//获取Iterator对象
        while(iterator.hasNext()){//判断集合中是否存在下一个元素
            Dog ele = (Dog)iterator.next();//输出集合中的元素
            System.out.println(ele);
        }
        System.out.println("--------------------");
        //方式二使用foreach
        for (Object o :list) {
            System.out.println(o);
        }
    }
}
相关推荐
一丝晨光4 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
天上掉下来个程小白7 分钟前
Stream流的中间方法
java·开发语言·windows
xujinwei_gingko18 分钟前
JAVA基础面试题汇总(持续更新)
java·开发语言
liuyang-neu19 分钟前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
一丝晨光30 分钟前
Java、PHP、ASP、JSP、Kotlin、.NET、Go
java·kotlin·go·php·.net·jsp·asp
罗曼蒂克在消亡33 分钟前
2.3MyBatis——插件机制
java·mybatis·源码学习
_GR1 小时前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
无限大.1 小时前
c语言200例 067
java·c语言·开发语言
余炜yw1 小时前
【Java序列化器】Java 中常用序列化器的探索与实践
java·开发语言
攸攸太上1 小时前
JMeter学习
java·后端·学习·jmeter·微服务