Data structures 为什么Hashmap的输出是任意的,而不是按照特定的顺序?为什么其排序顺序在插入时发生变化&;删除新节点?
请解释为什么hashmap会给出不可预测的输出?它根据什么对元素进行排序?为什么在插入/删除新元素时其输出会发生变化? 导入java.util.HashMap; 导入java.util.Iterator; 导入java.util.SetData structures 为什么Hashmap的输出是任意的,而不是按照特定的顺序?为什么其排序顺序在插入时发生变化&;删除新节点?,data-structures,hashmap,Data Structures,Hashmap,请解释为什么hashmap会给出不可预测的输出?它根据什么对元素进行排序?为什么在插入/删除新元素时其输出会发生变化? 导入java.util.HashMap; 导入java.util.Iterator; 导入java.util.Set public class Main6 { public static void main(String[] args) { HashMap<String, String> h
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"));
}
}
公共类main 6
{
公共静态void main(字符串[]args)
{
HashMap hMap=新的HashMap();
hMap.put(“10”、“1”);
hMap.put(“11”、“2”);
hMap.put(“12”、“3”);
hMap.put(“17”,“simran”);
hMap.put(“13”、“4”);
hMap.put(“14”、“5”);
Set st=hMap.keySet();
//圣雷沃(“12”);
迭代器itr=st.Iterator();
while(itr.hasNext())
System.out.println(itr.next());
//从集合中移除2个
//圣雷沃(“12”);
系统输出打印(hMap.containsKey(“12”));
}
}
HashMap
迭代顺序取决于对象哈希在bucket中的分布方式。当您添加一个新项目时,存储桶的数量可能会扩大,这将需要重新分配条目,这将重新排序所有内容
另外,作为一种安全措施,HashMap
的当前实现有一个随机散列模式(),该模式在某个阈值(jdk.map.althashing.threshold
)之后启用。这是为了阻止某类拒绝服务攻击,这些攻击涉及尝试查找哈希冲突。请先阅读哈希映射()。希望你能理解不可预知的顺序。