踩坑Java HashMap遍历
23-09-03 10:57
字数 2672
阅读 2919
重构PHP接口写出的bug,误以为HashMap遍历是有序的,说说怎么掉进陷阱的
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Map<String, Integer> map = new HashMap<>(3);
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
System.out.println("--------------------------------------------");
}
}
跑了多次,按顺序输出,看起来没问题,继续
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Map<TestEnum, Integer> map = new HashMap<>(3);
map.put(TestEnum.A, 1);
map.put(TestEnum.B, 2);
map.put(TestEnum.C, 3);
for (Map.Entry<TestEnum, Integer> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
System.out.println("--------------------------------------------");
}
}
@Getter
@AllArgsConstructor
public enum TestEnum {
A("A"),
B("B"),
C("C"),
;
private final String code;
}
看输出觉得没问题,于是没有继续验证,实际业务代码中是Map<TestEnum, Object>
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Map<TestEnum, Apple> map = new HashMap<>(3);
map.put(TestEnum.A, new Apple("one"));
map.put(TestEnum.B, new Apple("two"));
map.put(TestEnum.C, new Apple("three"));
for (Map.Entry<TestEnum, Apple> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
System.out.println("--------------------------------------------");
}
}
@Data
@AllArgsConstructor
public static class Apple {
private String name;
}
// 输出
key: C, value: Main.Apple(name=three)
key: A, value: Main.Apple(name=one)
key: B, value: Main.Apple(name=two)
可以看到顺序已经不是预想的那样了,此时可以换成LinkedHashMap保证顺序
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Map<TestEnum, Apple> map = new LinkedHashMap<>(3);
map.put(TestEnum.A, new Apple("one"));
map.put(TestEnum.B, new Apple("two"));
map.put(TestEnum.C, new Apple("three"));
for (Map.Entry<TestEnum, Apple> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
System.out.println("--------------------------------------------");
}
}
// 输出
key: A, value: Main.Apple(name=one)
key: B, value: Main.Apple(name=two)
key: C, value: Main.Apple(name=three)
1人点赞>
请登录后发表评论
相关推荐
文章归档
最新文章
最受欢迎
10-30 12:05
23-09-27 17:00
23-09-03 10:57
23-09-02 17:11
3 评论
3 评论
2 评论
转java了吗?