Ada*_*ter 5 java collections map semantics
假设你有这个代码:
Map<Foo, Bar> map = new HashMap<Foo, Bar>();
Foo foo = new Foo();
Bar bar = new Bar();
map.put(foo, bar);
Bar barReturned = map.get(foo);
Run Code Online (Sandbox Code Playgroud)
Java需要barReturned == bar
吗?也就是说,它的Java 需要的是barReturned
有相同的实例作为bar
?如果没有,预计会有什么语义?
该Javadoc中表明,barReturned == bar
必须是真实的,但我不是100%肯定的是:
V get(Object key)
返回指定键映射到的值,或者
null
此映射是否不包含键的映射.更正式地,如果此映射包含从键映射
k
到一个值v
,使得(key==null ? k==null : key.equals(k))
,则此方法返回v
; 否则它会返回null
.(最多可以有一个这样的映射.)如果此映射允许
null
值,则返回值null 不一定表示映射不包含键的映射; 地图也可能明确地将密钥映射到null
.containsKey操作可用于区分这两种情况.参数:
key
- 要返回其关联值的键返回:
值来指定键映射,或者
null
如果此映射不包含该键的映射关系
(强调我的)
编辑:据我所知,Map
与标准库捆绑在一起的实现遵循barReturned == bar
语义.我想知道的是,根据文档是否需要这种行为.例如,如果我编写自己的实现类,我是否还必须遵守这些语义Map
?
class Foo{
}
class Bar{
}
public class MapDemo {
public static void main(String[] args) {
Map<Foo,Bar> map = new HashMap<Foo,Bar>();
Foo foo = new Foo();
Bar bar = new Bar();
map.put(foo, bar);
System.out.println(bar == map.get(foo));
}
}
Run Code Online (Sandbox Code Playgroud)
返回真
HashMap
实现了Map
,但没有这样写。
/**
137 * Returns the value of the mapping with the specified key.
138 *
139 * @param key
140 * the key.
141 * @return the value of the mapping with the specified key, or {@code null}
142 * if no mapping for the specified key is found.
143 */
Run Code Online (Sandbox Code Playgroud)
但几乎每个实现都会这样做,我的意思是它维护相同的对象
归档时间: |
|
查看次数: |
535 次 |
最近记录: |