java - HashMap的keySet()顺序问题
阿神
阿神 2017-04-17 11:17:05
[Java讨论组]

每次都是 put 相同的值,那么 keySet 得到的 Key 的顺序都是固定的么?

我自己试的确是这样的,基本确定是固定的,看源码肯定更清楚了,自己懒。。。

我想这个 KeySet 顺序取决于 put 时散列值,这个散列值和什么相关呢,会不会换台机器或者换个 jdk 版本这个值就会有影响呢?

阿神
阿神

闭关修行中......

全部回复(1)
怪我咯

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;
    }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号