在最新的ConcurrentHashMap中有这么一个方法声明
@SuppressWarnings("unchecked")
public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
if (key == null || mappingFunction == null)
throw new NullPointerException();
return (V)internalComputeIfAbsent(key, mappingFunction);
}
相比 putIfAbsent,这个方法传入一个计算函数MappingFunction,而不是具体的值。这样只有在需要的时候调用这个MappingFunction创建值,而不是预先创建好。
很有用的一个新方法。但本文的重点不在此,MappingFunction<? super K, ? extends V> 的泛型声明吸引了我。
为什么不都使用用extends?super和extends区别在哪?
- super是声明下界,extends是声明上界
- 声明了下界的泛型容器只能add该泛型参数类型,声明了上界的泛型容器只能get该泛型参数类型
public static interface MappingFunction<K, V> {
/**
* Returns a non-null value for the given key.
*
* @param key the (non-null) key
* @return a non-null value
*/
V map(K key);
}
从上面的map中可见,MappingFunction<K,V>中的K在computeIfAbsent中声明ConcurrentHashMap<K,V>的K为其super 边界,V声明ConcurrentHashMap<K,V>的V为其extends边界。即map方法可以接收ConcurrentHashMap key的父类(包括边界),返回的value必须是ConcurrentHashMap value的子类(包括边界)。
- super用来限制传入的参数
- extends使用限制返回的参数
1万+



被折叠的 条评论
为什么被折叠?



