java 集合之Map

Map接口与Collection接口不同,这个接口的元素是“键值对”,键不可以重复,值可以重复。它的实现类,  HashMap HashTable LinkedHashMap

hashMap的特点是在判断键是否重复的时候采用哈希算法,因此要求作为HashMap键的对象,必须重写equals和hashCode方法,我们来看一下源码

public static void main(String[] args) {
	Map<String, String> map = new HashMap<String,String>();
	map.put("1992", "荷兰");
}
当我们new 一个HashMap的时候
/**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
/**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }
这两个参数为

/**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
原来new 一个HashMap的时候,会创建一个长度为Capacity的数组,默认长度为
1 << 4
左移4位,即2的4次幂,初始长度为16,初始负载因子为 0.75f ,这个数组可以存储元素的位置称为“bucket”,每个bucket都有下标,所以当我们要往进put的时候,它的顺序应该是这样的。

1.先求出键对象的hashCode

2.求出下标,用hashCode跟Capacity长度求模,算出来的就是坐标

3.如果坐标没有元素,直接插入,如果坐标有元素,这个时候才触发equals方法

4.如果相等,进行替换,如果不相等,往下一坐标插入元素。


那负载因子有什么用呢,我们都知道数组长度是固定的,刚开始默认设置长度为16,如果不够的话就要进行扩容,扩容为200,这里设定的是,当元素个数超过 长度*负载因子的时候就要扩容,例如 默认长度为16,负载因子为0.75,即元素个数>12的时候就要扩容,

Entry[] newTable = new Entry[newCapacity];


LinkedHashMap和Map的区别有点类似于LinkedHashSet和HashSet,区别,LinkedHashMap能保留键值对put Map的顺序。

HashTable也是Map的一个实现,它跟HashMap的区别有点类似 ArrayList 和 vector的区别

HashTable:

1.重量级,线程安全,效率低

2.null作为键或者值会抛异常

HashMap:
1.轻量级,线程不安全,效率高

2.允许null作为键或者值







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值