我们都知道Set(除了他们的这样的实现) doesn't guarantee of iteration ordering .So我试着用下面的示例代码来确保这一点。
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("******************************************************");
}
}我多次执行上面的代码,发现它正在按顺序打印记录。
我的问题是,如果java声称HashMap是无序的,那么为什么这些记录是按顺序打印的。如果有人能给我举例说明,那就太好了。
发布于 2012-09-13 15:40:09
每次的顺序都是相同的,因为字符串的散列代码不会改变,而您是以相同的顺序插入的。Hashmap是确定性的,所以如果您创建相同的hashmap并以相同的顺序插入内容,您将始终获得一致的排序。
Hashmap不能保证这种排序将保持一致的。如果您插入更多项,则在重新构建哈希表时,排序可能会完全改变。
发布于 2012-09-13 15:38:58
当您向映射中添加新元素时,通常会发生重新排序。如果调整了贴图的大小,则顺序可能会更改。
发布于 2012-09-13 15:41:05
这是因为字符串散列代码
public int hashCode() {
int h = hash;
if (h == 0 && count > 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}对于一个字母串,它将是字符的h= 31*0+numeric值,因此所有散列码都是1)低2)与字母相同的顺序。因此,它们很可能会按此顺序返回。
https://stackoverflow.com/questions/12401499
复制相似问题