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());

}

原理实现


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循环:

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.

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);
        }
    }
}


     

  • 24
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值