Java中的Map实现

源码来自JDK8

Map接口
public interface Map<K,V> {
	interface Entry<K,V> {
	}
}
HashMap
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
	//容量参数
	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始化容量 aka 16
	static final int MAXIMUM_CAPACITY = 1 << 30;// 最大容量
	static final float DEFAULT_LOAD_FACTOR = 0.75f;

	//链表转红黑树参数
	static final int TREEIFY_THRESHOLD = 8;
	static final int UNTREEIFY_THRESHOLD = 6;
	static final int MIN_TREEIFY_CAPACITY = 64;

	//数据存储的结构
	static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    }
    transient Node<K,V>[] table;
}
LinkedHashMap
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>{

	transient LinkedHashMap.Entry<K,V> head;
	transient LinkedHashMap.Entry<K,V> tail;

	static class Entry<K,V> extends HashMap.Node<K,V> {
		Entry<K,V> before, after;
	}

}
TreeMap
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable{
	private final Comparator<? super K> comparator;
	private transient Entry<K,V> root;//红黑树的根节点

	public TreeMap() {
        comparator = null;
    }

	static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;
	}

}

TreeMap的底层数据结构是红黑树。

ConcurrentModificationException

在Java开发过程中,遍历集合的同时对集合进行修改就会出现java.util.ConcurrentModificationException异常。以HashMap中的代码展示:

@Override
public void forEach(BiConsumer<? super K, ? super 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.key, e.value);
        }
        if (modCount != mc)
            throw new ConcurrentModificationException();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值