踩坑Java HashMap遍历

23-09-03 10:57 字数 2672 阅读 1275

重构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人点赞>
关注 收藏 改进 举报
3 条评论
排序方式 时间 投票
Up骚年

转java了吗?

danton
是的,php项目只剩维护和少量迭代
Up骚年
回复 danton: 厉害啊,我也在看Java的视频。
请登录后发表评论