java - How do I ask for a parameter to be a mutable Map? -
i have function accepts map
of parameters, adds them before using them:
public string dorequest(string endpoint, map<string, string> parameters) { parameters.put("limit", "50"); ... }
it's convenient create map using guava's immutablemap.of()
:
dorequest("/comments", immutablemap.of("filter", "true"));
however, throws java.lang.unsupportedoperationexception
@ runtime.
two questions:
1) can declare dorequest
in way example hashmap
, treemap
fine using immutablemap
compile time error?
2) inside dorequest
, how detect it's immutablemap
, run params = maps.newhashmap(params)
?
1) can declare dorequest in way example hashmap , treemap fine using immutablemap compile time error?
no. immutablemap
implements map
, can't compile time error. problem map.put
, allows throw. it'd better have map
without put
, mutablemap
interface... there's nothing in java software around relies on it.
2) inside dorequest, how detect it's immutablemap, run params = maps.newhashmap(params)?
you'd better there's collections.unmodifiablemap
, implement map
refusing put
.
if you're concerned performance, you'll need instanceof
check.
Comments
Post a Comment