为什么Hashmap的输出是任意的,而不是以特定的顺序?为什么它的排序顺序在插入&删除新节点? [英] why the output of the Hashmap is arbitary, not in a specific order? why its sorting order gets change on insertion & deletion of new node?

查看:227
本文介绍了为什么Hashmap的输出是任意的,而不是以特定的顺序?为什么它的排序顺序在插入&删除新节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释hashmap为何产生不可预测的输出?在哪个基础上对元素进行排序?为什么当我们插入/删除一个新元素时它的输出发生变化?
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

  public class Main6 
{
public static void main(String [] args)
{
HashMap< String,String> hMap = new HashMap< String,String>();

hMap.put(10,One);
hMap.put(11,Two);
hMap.put(12,Three);
hMap.put(17,simran);
hMap.put(13,four);
hMap.put(14,five);

Set st = hMap.keySet();
//st.remove(\"12);
Iterator itr = st.iterator(); (itr.hasNext())
System.out.println(itr.next());

while

//从集合
删除2 //st.remove(\"12);


System.out.println(hMap.containsKey(12));
}
}


解决方案

HashMap 迭代顺序取决于对象哈希如何在桶之间分配。当你添加一个新的项目时,桶的数量可能会扩大,这将需要重新分配项目,这将重新排列所有内容。



另外,作为安全措施, HashMap 的当前实现具有随机哈希模式(alternative hashing),它在特定阈值( jdk.map.althashing.threshold )后启用。这是为了阻止某种类型的拒绝服务攻击,其中涉及试图发现散列冲突。

Please explain why the hashmap gives unpredictable output? On which basis it sorts the elements ? why its output changes when we insert / delete a new element? import java.util.HashMap; import java.util.Iterator; import java.util.Set;

    public class Main6 
    {
        public static void main(String[] args) 
        {
            HashMap<String, String> hMap = new HashMap<String, String>();

            hMap.put("10", "One");
            hMap.put("11", "Two");
            hMap.put("12", "Three"); 
            hMap.put("17", "simran");
            hMap.put("13", "four");
            hMap.put("14", "five");

            Set st = hMap.keySet();
            //st.remove("12");
            Iterator itr = st.iterator();

            while (itr.hasNext())
            System.out.println(itr.next());

            // remove 2 from Set
                //st.remove("12");


            System.out.println(hMap.containsKey("12"));
        }
    }

解决方案

HashMap iteration order depends on how the object hashes are distributed among the buckets. When you add a new item, the number of buckets may be expanded, which will require the entries to be redistributed, which will reorder everything.

Also, as a security measure, current implementations of HashMap have a randomised hashing mode ("alternative hashing") which is enabled after a certain threshold (jdk.map.althashing.threshold). This is to thwart a certain class of denial-of-service attacks which involve trying to find hash collisions.

这篇关于为什么Hashmap的输出是任意的,而不是以特定的顺序?为什么它的排序顺序在插入&amp;删除新节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆