单元测试偶然发现的Map一个问题
Map<String,String> map1 = new HashMap<>();map1.put("aaa", "foo");map1.put("bbb", "bar");map1.put("ccc", "foobar");System.out.println(map1); // {aaa=foo, ccc=foobar, bbb=bar}Map<String,String> map2 = new HashMap<>(map1);assertEquals(map1.values().toArray(new String[]{}), map2.values().toArray(new String[]{}));System.out.println(map2); // {aaa=foo, ccc=foobar, bbb=bar}Map<String,String> map3 = new HashMap<>(3); //显式指定了大小map3.putAll(map1);System.out.println(map3); // {bbb=bar, ccc=foobar, aaa=foo}assertEquals(map1.values().toArray(new String[]{}), map3.values().toArray(new String[]{})); // 判等失败
可见如果显式指定了map容器大小 会影响key的索引。如下所示
默认大小
key | index |
---|---|
aaa | 3 |
ccc | 10 |
bbb | 14 |
显式指定了大小3
key | index |
---|---|
aaa | 3 |
ccc | 2 |
bbb | 2 |