02 迭代器

1 Iterator 的基本使用

迭代器统一了对集合的访问方式。注意迭代器在集合层次中的位置。

  1. 使用 iterator() 方法要求集合返回一个 IteratorIterator 将准备好返回序列中的第一个元素。
  2. 使用 next() 方法获得序列中的下一个元素。
  3. 使用 hasNext() 方法检查序列中是否还有元素。
  4. 使用 remove() 方法将迭代器最近返回的那个元素删除。注意,在调用 remove() 之前必须先调用 next()
package com.hcong.collections;

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

/**
 * @Classname SimpleIteration
 * @Date 2023/4/4 16:16
 * @Created by HCong
 */
public class SimpleIteration {
    public static void main(String[] args) {
        // 1.迭代器遍历
        Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        Iterator<Integer> it = collection.iterator();
        while (it.hasNext()) {
            Integer next = it.next();
            System.out.print(next + " ");
        }
        System.out.println();

        // 2.for-in
        for (Integer i : collection) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 3.迭代器删除元素
        it = collection.iterator();
        for (int i = 0; i < 5; i++) {
            it.next();
            it.remove();
        }
        System.out.println(collection);
    }
}

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 
[6, 7, 8, 9, 10]

2 ListIterator 的基本使用

ListIterator 是一个更强大的 Iterator 子类型,它只能由各种 List 类生成。Iterator 只能向前移动,而 ListIterator 可以双向移动。它可以生成迭代器在列表中指向位置的后一个和前一个元素的索引,并且可以使用 set() 方法替换它访问过的最近一个元素。可以通过调用listIterator() 方法来生成指向 List 开头处的 ListIterator ,还可以通过调用 listIterator(n) 创建一个一开始就指向列表索引号为 n 的元素处的 ListIterator

package com.hcong.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

/**
 * @Classname ListIteration
 * @Date 2023/4/4 16:35
 * @Created by HCong
 */
public class ListIteration {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G"));
        ListIterator<String> lit = list.listIterator();
        while (lit.hasNext()) {
            String next = lit.next();
            System.out.println(next + " " + lit.nextIndex() + " " + lit.previousIndex() + " ");
        }
        System.out.println();
    }
}

A 1 0 
B 2 1 
C 3 2 
D 4 3 
E 5 4 
F 6 5 
G 7 6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是聪聪黄吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值