代码:
import java.util.HashMap;
import java.util.Map;
public class TQ {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Map<String,String> hm= new HashMap<String,String>();
hm.put("002", "孙悟空");
hm.put("005", "白龙马");
hm.put("003", "猪八戒");
hm.put("004", "沙悟净");
hm.put("001", "唐 僧");
System.out.println("原始哈希映射:"+hm);
}
}
这个顺序是无法保证的,升序只能理解为因为它们都是字符串常量,所以它们的地址按照某种循序排列,导致hash存在顺序
但是你插入别的,特别是运算的道德字符串作为key而不是这种写死的,就未必了
要固定顺序,参考:
https://blog.csdn.net/nju_mc/article/details/52931468
或者人为对keyset排序
1.HashMap输出是无序的,无序说的是输出集合时的顺序跟其插入元素时的顺序不同,且当继续插入新元素时,此时输出元素的顺序可能跟插入新元素前输出元素的顺序不同;
2.在put插入元素时,HashMap是根据键值key的hashCode()方法来计算下标位置,再存放在数组里;
3.String的hashCode方法如下
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
'001''002''003''004''005'字符串的hashCode值是连续的,所以输出顺序恰好是连续的