Consider this piece of code:
Set<String> mySet = new HashSet<String>(){{add("foo");add("boo");}};
or for the HashMap:
Map<String,String> myMap = new HashMap<String,String>(){{put("foo","bar");put("boo","jar");}};
Pros are simply to find: less lines of code, conciseness. But what are the cons?
UPD: The question is not only about sets, but about all types of collections, added Map to illustrate this.
When you do that, you are creating an anonymous subclass of HashSet, which means you are unnecessarily polluting your code base with classes that don’t do anything new.
How about this instead?
Or alternatively, use Guava‘s
Setsclass. It has factory methods to initialize different kinds of sets:With Maps it’s trickier, but you can use
ImmutableMap:or (mutable version)
Without external libraries, you can still initialize a Map with a single entry:
but that be one ugly beast, if you ask me.
Guava has several Factory classes like this:
Sets,Maps,Lists,Multimaps,Multisets,Ranges