You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TreeMap的firstEntry()与higherEntry(0)返回的Entry对象不相等?

问题原因及解决办法

Java里==比较的是对象的内存引用地址,而TreeMap的higherEntry()和firstEntry()会返回不同的Map.Entry实例——哪怕这两个实例的键值对内容完全一样,它们在内存里的地址也不一样,所以用==判断会返回false。

要让判断返回true,直接把==换成equals()方法就行,因为Map.Entry接口的equals()方法已经默认实现为比较键和值是否都相等(键和值分别用各自的equals()方法判断)。

修改后的代码如下:

public static void main(String[] args) {
    TreeMap<Integer,Integer> map=new TreeMap<>();
    map.put(1,2);
    Map.Entry<Integer, Integer> e = map.higherEntry(0);
    System.out.println(e.equals(map.firstEntry()));
}

运行这段代码就会输出true。

内容的提问来源于stack exchange,提问作者tasty0tomato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:24:51