在java中,我应该如何创建具有不可修改键的Map<String,String>
,同时保持值可修改。
我想通过一个接口让这个Map<String,String>
为其他人添加/更改Map值,但是无法更改Map键。
更高级别问题的背景是我有一个变量名列表/一组(树状结构)(表示为java String),我想在java接口的另一端编写代码以便能够填充每个变量名的别名(也是字符串)。我希望有这个接口的多个实现,因此命名树层次结构可以是不同的方式来适应不同的情况。让接口实现填充Map<String,String>
,其中包含一堆已经固定的键(并且可能包含值的默认值)并允许它修改值(但不是键),这似乎是最好的方法。我正在创建名称和别名之间的映射,因此Map<>
是有道理的。
回到较低级别的问题。我希望我的代码类似于:
public class MyClass
{
public interface IMyMapper
{
void build(Map<String,String> mapping);
}
IMyMapper mapper;
// How I'd like to use it
void work()
{
Map<String,String> map ;
// Magic something like Collections unmodifiableMap, but only for keys
// Maybe my question should be how this magic for UnmodifiableMap works, so I could reproduce it??
mapper.build(map);
// Because Maps<> are by reference, changed they made (to the values) would be reflected here
}
}
public class TheirClass implements MyClass.IMyMapper
{
@Override
public void build(Map<String,String> mapping)
{
// use mapping like Map<String,String> without extra/foreign classes
// but not be able to modify the Map keys
// only be able to change the Map values
// Should be able to use all of the awesome Map stuff, like foreach, values, compute
}
}
我知道有Collections unmodifiableMap(Map<> m)
,但这也使得值无法修改。如果我的值是可变对象,那么我可以修改它们但是我想坚持使用Strings
(避免为单个String成员创建带有set / get的Class,或者使用public String成员创建类似结构的类)
AKA,我想避免创建自己的可变类值,并使用Collections unmodifiableMap()
来创建密钥,value references
不可修改:
// mutable reference to a String
public class ExtraWorkForForEveryone
{
public String value;
public void setValue(String value) { ... }
public String getValue() { ... }
}
// and then use:
void work()
{
Map<String,ExtraWorkForEveryone> map;
map = Collections.unmodifiableMap( ... );
// because Collections.unmodifiableMap() only stops them from changing the Map references,
// the interfacer could still change the ExtraWorkForEveryone internals.
// so they could not change keys refs or value refs, but they could change value data.
mapper.build(map);
// Because Maps<> are by reference, changed they made (to the values) would be reflected here
}
我可以扩展或实现我自己的Map,然后(比如Collections unmodifiableMap()
如何)覆盖所有可以改变键UnsupportedOperationException
的方法。但是使用Java 8,已经有大量的方法使用Lambda函数添加,这对于接口实现者来说很有用,只要它们无法更改密钥。
AKA,我想避免这种冗长且容易出错的技术:
public final class FinalHashMap extends HashMap
{
@Override // anything that might be able to change the Map Keys
so_many_methods_and_edge_cases()
{ throws UnsupportedOperationException }
}
是否存在仅允许更改Maps<>
的数据?
创建类似Map<String,String>
的具有不可修改键但可修改值的内容的其他选项有哪些?如果可能的话,我对良好的编码实践感兴趣。
答案 0 :(得分:4)
好像您正在寻找Proxy Pattern。
详细答案:
我们的想法是使用名为 proxy 的内容与地图进行互动。代理将拦截对地图的所有调用;您应该只能通过代理与地图交互。它充当客户端和地图之间的接口。
代理是你是什么&#34;包装&#34;的骨架。由于您要为地图创建代理,因此代理应实现Map
接口:
class ImmutableMap<K, V> implements Map<K, V> {
private Map<K, V> map;
public ImmutableMap(Map<K, V> map) {
this.map = new HashMap<>(map); // detach reference
}
//implement methods from Map
}
大多数方法只是望远镜到map
。修改您需要的方法,以防止删除键或向地图添加新键,例如put
,putAll
和remove
:
final class ImmutableMap<K, V> implementsMap<K, V> {
private Map<K, V> map;
public ImmutableMap(Map<K, V> map) {
this.map = new HashMap<>(map);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public V get(Object key) {
return map.get(key);
}
@Override
public V put(K key, V value) {
if(!map.containsKey(key)) {
throw new IllegalArgumentException("Cannot add new keys!");
}
return map.put(key, value);
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException("You cannot remove entries from this map!");
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for(K key : map.keySet()) {
if(!this.map.containsKey(key)) {
throw new IllegalArgumentException("Cannot add new keys to this map!");
}
}
this.map.putAll(map);
}
@Override
public void clear() {
throw new UnsupportedOperationException("You cannot remove entries from this map!");
}
@Override
public Set<K> keySet() {
return Collections.unmodifiableSet(map.keySet());
}
@Override
public Collection<V> values() {
return Collections.unmodifiableSet(map.values()); //prevebt changing values to null
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
//to allow modification of values, create your own ("immutable") entry set and return that
return Collections.unmodifiableSet(map.entrySet());
}
}
注释记号:
Collections.unmodifiableSet
。这可以确保如果某人试图修改从地图返回的集合,则会抛出UnsupportedOperationException
创建一个包含传递给构造函数的地图值的新Map
会阻止客户端使用传递给它的地图修改ImmutableMap
。
答案 1 :(得分:0)
您可能希望限制地图的大小
过度使用你的put方法你可以使用
if (map.size() == maxEntries) {
throw some exception;