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

Java多键映射同一值:避免重复存储的内存优化方案问询

Answer

Great question! Let's clear up a few things first and then show you exactly how to make multiple keys point to the same value instance in memory.

First, your concern about duplicate memory usage is valid in some cases. When you write:

Map<Integer, Integer> map = new HashMap<>();
map.put(65, 600);
map.put(70, 600);

By default, Java's autoboxing for integers outside the cached range (-128 to 127) will create separate Integer objects for each 600 you pass. That means two distinct instances of Integer (both holding the value 600) are stored in memory—one for each map entry.

To fix this and make all target keys reference the same value instance, simply create a single value object and reuse it across all put calls:

// Create one shared instance of the value
Integer sharedScore = 600; // Or explicitly use Integer.valueOf(600)

Map<Integer, Integer> map = new HashMap<>();
map.put(65, sharedScore);
map.put(70, sharedScore);

Now both entries in the map point to the exact same Integer object. This way, the value 600 is only stored once in memory.

Extra Notes:

  • For immutable types like Integer, even if you have duplicate instances, the memory overhead is minimal. But reusing the same instance is still a clean practice, especially if you're dealing with large numbers of duplicate values.
  • If you were using mutable objects (like a custom class), reusing the same instance becomes even more critical—any changes to that object will be reflected across all keys that map to it, which might be desired or not depending on your use case.
  • If you have a huge number of keys mapping to the same value, you could also consider a reverse mapping (like a Map<Integer, List<Integer>> where the key is the value and the value is a list of keys), but that's a different approach and only makes sense if you need to frequently look up all keys for a given value.

Hope that solves your problem!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:51:17