HashMap.Entry源码

这个是HashMap的内部类,通过EntrySet用来存储所有的map的值。为什么我们用Iterator可以来进行遍历map的数据?原因就是有这个内部类,EntrySet  ---> AbstractSet  -->  Set  --> Collection  -->  Iterator;   (-->  表示继承或是实现关系)

这样们就可以通过Iterator来迭代出HashMap的值了

    // 内部内,EntrySet集合
    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
    	// 集合的大小
        public final int size()                 { return size; }
        // 清空数据
        public final void clear()               { HashMap.this.clear(); }
        // 返回迭代器
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        // 判断是否包含传入 的key
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        // 通过传入 的数据,移除对应的数据
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        // 
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        // 对应集合进行遍历,对其中的数据 进行操作
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

迭代测试代码:

		Iterator<Entry<String, String>>  iterator = map.entrySet().iterator();
		
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			
			String key = entry.getKey();
			System.out.println(key);
			System.out.println(entry.getValue());
			System.out.println(entry.hashCode());
		}
		

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值