How to code the set method of a Map with another Map as value?
I normally do this to set a ne开发者_Python百科w Map to a private variable:
public static void setListaClausulas(Map<String, Clausula> nvLista) {
listaClausulas = new TreeMap<String, Clausula>(nvLista);
}
I suppose this is ok to set a new copy of the nvLista
and all it's members and not a reference, is it?
But now I have a Map inside another Map and I'm doing this:
public static void setListaClausulas(Map<String, Map<String, Clausula>> nvLista) {
listaClausulas = new TreeMap<String, Map<String, Clausula>>(nvLista);
}
Is this the correct way to do it or do you recommend something else? What I want is to set a new copy of nvLista
(and all it's elements) and not copy just the reference.
I guess you are worried about the maps being passed in your method parameter will be mutated?
You need to create a deep-copy of the parameter. Various approaches are discussed in this SO question, deep-clone-utility-recomendation
EDIT: In response to comment, here's a coded version. This doesn't deep copy the Clausula
instances, since they were not copied before - I'm assuming they're immutable.
public Map<String, Map<String, Clausula>> deepCopy(Map<String, Map<String, Clausula>> nvLista)
{
Map<String, Map<String, Clausula>> target = new TreeMap<String, Map<String, Clausula>>();
for (String key: nvLista.keySet()) {
Map<String, Clausula> value = nvLista.get(key);
target.put(key, new TreeMap<String,Clausula>(value));
}
return target;
}
However, nesting collection types like this quickly becomes unreadable. If you can change the code, it may help readability to create a wrapper object for the innermost map.
Deep copying is hard for general case, but you could do this to solve your particular problem:
static Map< String, Map< String, Clausula > > deepCopy (
final Map< String, Map< String, Clausula > > source
)
{
final TreeMap< String, Map< String, Clausula> > result =
new TreeMap< String, Map<String,Clausula> >( );
for (
final Map.Entry< String, Map< String, Clausula> > cur :
source.entrySet( )
)
{
result.put(
cur.getKey( ),
new TreeMap< String, Clausula >( cur.getValue( ) )
);
}
return result;
}
精彩评论