I normally do this to set a new 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
Clausulainstances, since they were not copied before – I’m assuming they’re immutable.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.