hashcode() equals()看懂一片够了

本文探讨了在Java中使用HashMap实现有序存取的问题。通过创建一个Map实例并插入三个Test对象,虽然Map本身不保证顺序,但在迭代时发现由于Test对象的equals始终返回false和hashCode始终返回相同值,导致预期的有序存取无法实现。文章着重分析了equals和hashCode方法在HashMap中的作用,并提醒读者注意这两个方法的正确实现对于Map的行为至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 3 5 存map 实现有序存取

Map<Test, Integer> map = new HashMap<>();
        Test test1 = new com.myzy.auth.controller.Test();
        test1.setCode(1);
        Test test2 = new com.myzy.auth.controller.Test();
        test2.setCode(2);
        Test test3 = new com.myzy.auth.controller.Test();
        test3.setCode(3);
        map.put(test1, 1);
        map.put(test2, 1);
        map.put(test3, 1);
        Iterator<Map.Entry<Test, Integer>> iterable = map.entrySet().iterator();
        while (iterable.hasNext()) {
            Map.Entry<Test, Integer> entry = iterable.next();
            System.out.println(entry.getKey());
        }
public boolean equals(int code) {
        return false;
    }

    public int hashCode() {
        return 100;
    }

重写equals方法为始终不相等,重写hashcode方法始终为相等

看懂的给个回复!!!!!!!!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值