Is there an implementation of java.util.Map that only allows a value to be read once? What I'd like to do is something like this:
Map map = new ReadOnceMap();
map.put("key", "value")
System.out.println(map开发者_JAVA技巧.get("key")); // prints "value"
System.out.println(map.get("key")); // prints null
EDIT: requirements:
- existing implementation
- values are guaranteed to be read at most one time
map.remove() should give you the behaviour you want
Map map = new ReadOnceMap();
map.put("key", "value")
System.out.println(map.remove("key")); // prints "value"
System.out.println(map.remove("key")); // prints null
Something like this?
public class GetOnceHashMap<K,V> extends HashMap<K,V> {
@Override
public V get(Object key) {
return remove(key);
}
@Override
public Collection<V> values() {
Collection<V> v = new ArrayList<V>(super.values());
clear();
return v;
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> e = new HashSet<Map.Entry<K,V>>(super.entrySet());
clear();
return e;
}
}
Just call the remove() method instead of the get() method. The remove() method returns the object being removed from the map. So, the first time you'll get your object and after that it will return null.
Here's an implementation I came up with.
NOTE: This is not really production-quality because I'm counting on new ArrayList
and new HashSet
to eagerly (not lazily) read the values. To make this production quality, I would get rid of inheritance and use a dynamic proxy or object composition.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ReadOnceMap<K, V> extends HashMap<K, V> {
@Override
public V get(Object key) {
return remove(key);
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> entrySet = new HashSet<Map.Entry<K, V>>(super.entrySet());
clear();
return entrySet;
}
@Override
public Collection<V> values() {
Collection<V> values = new ArrayList<V>(super.values());
clear();
return values;
}
}
精彩评论