What are the cons of using in-place collection initializers in Java -
What are the cons of using in-place collection initializers in Java -
consider piece of code:
set<string> myset = new hashset<string>(){{add("foo");add("boo");}}; or hashmap:
map<string,string> mymap = new hashmap<string,string>(){{put("foo","bar");put("boo","jar");}}; pros find: less lines of code, conciseness. cons?
upd: question not sets, types of collections, added map illustrate this.
when that, creating anonymous subclass of hashset, means unnecessarily polluting code base of operations classes don't new.
how instead?
set<string> set = new hashset<string>(arrays.aslist("foo", "bar")); or alternatively, utilize guava's sets class. has mill methods initialize different kinds of sets:
set<string> set = sets.newhashset("foo", "bar"); with maps it's trickier, can utilize immutablemap:
map<string,string> mymap = immutablemap.of("foo","bar","boo","jar"); or (mutable version)
map<string,string> mymutablemap = maps.newhashmap(immutablemap.of("foo","bar","boo","jar")); without external libraries, can still initialize map single entry:
map<string,string> mymap = new hashmap<string, string>( collections.singletonmap("foo","bar") ); but 1 ugly beast, if inquire me.
upd: question not sets, types of collections, added map illustrate this.
guava has several mill classes this:
sets, maps, lists, multimaps, multisets, ranges
java collections map initialization set
Comments
Post a Comment