为了账号安全,请及时绑定邮箱和手机立即绑定

HashMap的keySet()顺序问题

HashMap的keySet()顺序问题

陪伴而非守候 2019-03-30 23:19:16
每次都是 put 相同的值,那么 keySet 得到的 Key 的顺序都是固定的么?我自己试的确是这样的,基本确定是固定的,看源码肯定更清楚了,自己懒。。。我想这个 KeySet 顺序取决于 put 时散列值,这个散列值和什么相关呢,会不会换台机器或者换个 jdk 版本这个值就会有影响呢?
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

put 源码:


public V put(K key, V value) {

    if (key == null)

        return putForNullKey(value);

    int hash = hash(key.hashCode());

    int i = indexFor(hash, table.length);

    for (Entry<K,V> e = table[i]; e != null; e = e.next) {

        Object k;

        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

            V oldValue = e.value;

            e.value = value;

            e.recordAccess(this);

            return oldValue;

        }

    }


    modCount++;

    addEntry(hash, key, value, i);

    return null;

}

在 foreach 循环中,隐式调用的 nextEntry 源码:


    final Entry<K,V> nextEntry() {

        if (modCount != expectedModCount)

            throw new ConcurrentModificationException();

        Entry<K,V> e = next;

        if (e == null)

            throw new NoSuchElementException();


        if ((next = e.next) == null) {

            Entry[] t = table;

            while (index < t.length && (next = t[index++]) == null)

                ;

        }

    current = e;

        return e;

    }


查看完整回答
反对 回复 2019-04-15
  • 1 回答
  • 0 关注
  • 357 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号