apache commons-collections 中我最喜欢的一个是 LazyMap,它在执行map.get(newKey); // Will not return null!
.
为什么谷歌收藏没有相同的?
apache commons-collections 中我最喜欢的一个是 LazyMap,它在执行map.get(newKey); // Will not return null!
.
为什么谷歌收藏没有相同的?
从 10.0 开始,guava 有了一个新的类CacheBuilder,它与 gwt 兼容。
我建议自己写
public class LazyMap<K, V> extends ForwardingMap<K, V> {
final Function<? super K, ? extends V> factory;
final Map<K, V> delegate;
public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Supplier<? extends V> supplier) {
return new LazyMap<>(map, supplier);
}
public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Function<? super K, ? extends V> factory) {
return new LazyMap<>(map, factory);
}
private LazyMap(final Map<K, V> map, final Function<? super K, ? extends V> factory) {
this.factory = factory;
this.delegate = map;
}
private LazyMap(final Map<K, V> map, final Supplier<? extends V> supplier) {
this.factory = Functions.forSupplier(supplier);
this.delegate = map;
}
@Override
protected Map<K, V> delegate() {
return delegate;
}
@Override
public V get(final Object key) {
if (delegate().containsKey(key) == false) {
@SuppressWarnings("unchecked")
final K castKey = (K) key;
final V value = factory.apply(castKey);
delegate().put(castKey, value);
return value;
}
return delegate().get(key);
}
}