java map put返回值,当通过Map.put(K,V)添加一个值时,是否必须通过Map.get(K)返回相同的实例?...

Suppose you have this code:

Map map = new HashMap();

Foo foo = new Foo();

Bar bar = new Bar();

map.put(foo, bar);

Bar barReturned = map.get(foo);

Does Java require that barReturned == bar? That is, does Java require that barReturned be the same instance as bar? If not, what semantics are expected?

The Javadoc suggests that barReturned == bar must be true, but I'm not 100% sure:

V get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Parameters:

key - the key whose associated value is to be returned

Returns:

THE VALUE TO WHICH THE SPECIFIED KEY IS MAPPED, or null if this map contains no mapping for the key

(Emphasis mine)

Edit: I understand that the implementations of Map that come bundled with the standard library adhere to the barReturned == bar semantics. What I want to know is whether or not this behavior is required as per the documentation. For example, must I also adhere to these semantics if I write my own class that implements Map?

解决方案

If you are asking whether you can break that relation, i think the answer is "yes". for instance, if you were implementing a Map which acted like a persistent cache, a specific value may be written to disk if not used in a while, then reloaded later. you will not have reference equality in that situation, but that's okay. obviously, you would want to document any deviations from standard behavior, but i don't think this is out of the realm of a reasonable usage of a Map.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值