【Map】Map集合的遍历:

本文详细介绍了Java中Map集合的遍历方法,并提供了完整的示例代码。解释了Map.Entry的概念及如何通过迭代器获取Map.Entry对象,展示了如何使用增强for循环遍历Map。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.问题:
Map集合的遍历:
2.源代码:
(拷贝可直接运行,建议自己敲一遍)

public class MapForeach {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<String,String>();
        map.put("1","A");
        map.put("2","B");
        map.put("3","C");
        map.put("4","D");
        map.put("5","E");
        map.put("6","F");
        for (Map.Entry<String,String> entry:map.entrySet()){
            System.out.println(entry.getKey()+"---------->"+entry.getValue());
        }
    }
}

3.截图:
这里写图片描述
4.总结:
其实很简单;我们来看看源码:

    /**
     * A map entry (key-value pair).  The <tt>Map.entrySet</tt> method returns
     * a collection-view of the map, whose elements are of this class.  The
     * <i>only</i> way to obtain a reference to a map entry is from the
     * iterator of this collection-view.  These <tt>Map.Entry</tt> objects are
     * valid <i>only</i> for the duration of the iteration; more formally,
     * the behavior of a map entry is undefined if the backing map has been
     * modified after the entry was returned by the iterator, except through
     * the <tt>setValue</tt> operation on the map entry.
     * @see Map#entrySet()
     * @since 1.2
     */
    interface Entry<K,V> {
        /**
         * Returns the key corresponding to this entry.
         * @return the key corresponding to this entry
         * @throws IllegalStateException implementations may, but are not
         *         required to, throw this exception if the entry has been
         *         removed from the backing map.
         */

一个Map的Entry就是一个Key-Value键值对;而EntrySet方法返回的是一个map的视图集合,其元素就是其类,唯一包含与map entry相关的是用迭代器;Map.Entry对象仅可以通过迭代器来获得;更确切地说,如果返回的map在entry被迭代器返回之前被改变了,map entry的行为是未定义的,除非通过setValue对map entry进行操作;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陶洲川

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

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

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

打赏作者

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

抵扣说明:

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

余额充值