Java集合 问题集中

import java.util.*;
public class CollectionEach {
    public static void main(String[] args) {
        Collection books = new HashSet();

        books.add("书1");
        books.add("书2");
        books.add("书3");
        books.add("书4");
        Iterator it = books.iterator();
        while(it.hasNext()) {
            String book = (String)it.next();
            System.out.println(book);
            if (book == "书3") {
                System.out.println("出现书3,删除");
                it.remove();
            }

            if (book == "书2") {
                System.out.println("出现书2,删除");
                books.remove(book);
                // 出现ConcurrentModificationException异常,
                //使用Iterator迭代过程中,集合元素不能被改变,只有通过Iterator的remove()方法删除才可以
            }
        }
        System.out.println(books);
    }
}

编译运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值