ami*_*ngh 1 java collections hashmap set
我们都知道迭代排序的Set(除了他们的这种实现)doesn't guarantee
.所以我试着通过下面的示例代码确保这一点.
public static void main(String[] args) throws InterruptedException {
Map<String,String> lMap=new HashMap<String, String>();
lMap.put("A", "A");
lMap.put("B", "B");
lMap.put("C", "C");
lMap.put("D", "D");
lMap.put("E", "E");
lMap.put("F", "F");
lMap.put("G", "G");
lMap.put("H", "H");
lMap.put("I", "I");
lMap.put("J", "J");
lMap.put("K", "K");
lMap.put("L", "L");
for(int i=0;i<10000;i++){
Thread.sleep(100);
Set<Entry<String, String>> entrYset=lMap.entrySet();
for(Map.Entry<String, String> e:entrYset){
System.out.println(e.getKey()+" , "+e.getValue());
}
System.out.println("******************************************************");
}
}
Run Code Online (Sandbox Code Playgroud)
我多次执行上面的代码,发现它按顺序打印记录.
我的问题是,如果java声称HashMap是无序的,那么为什么这些记录按顺序打印.如果有人可以给我一些理由,那将是很好的.
每次的顺序都是相同的,因为字符串的哈希码不会改变,并且您以相同的顺序插入.Hashmap是确定性的,因此如果您创建相同的hashmap并以相同的顺序插入内容,您将始终获得一致的排序.
Hashmap不保证此排序将保持一致.如果插入更多项,则在重建哈希表时,排序可能会完全改变.
归档时间: |
|
查看次数: |
228 次 |
最近记录: |