why the output of the Hashmap is arbitary, not in

2020-05-09 18:30发布

问题:

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"));
        }
    }

回答1:

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.