Reputation: 10151
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.
Upvotes: 1
Views: 2342
Reputation: 221106
Con: This will result in an anonymous class, which has to be loaded by the class loader. If you do that 500'000 times, I'm sure you'll run into OutOfMemoryExceptions
Upvotes: 3
Reputation: 10781
They don't work with gson anymore.
Gson gson = new Gson();
Map<String, Object> m;
m = new HashMap<String, Object>(){{ put("a", "b"); }};
System.out.println(gson.toJson(m)); // null
m = new HashMap<String, Object>();
m.put("a", "b");
System.out.println(gson.toJson(m)); // {"a":"b"}
Upvotes: 0
Reputation: 299048
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?
Set<String> set = new HashSet<String>(Arrays.asList("foo", "bar"));
Or alternatively, use Guava's Sets
class. It has factory methods to initialize different kinds of sets:
Set<String> set = Sets.newHashSet("foo", "bar");
With Maps it's trickier, but you can use 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, you can still initialize a Map with a single entry:
Map<String,String> myMap = new HashMap<String, String>(
Collections.singleTonMap("foo","bar")
);
but that be one ugly beast, if you ask me.
UPD: The question is not only about sets, but about all types of collections, added Map to illustrate this.
Guava has several Factory classes like this:
Sets
, Maps
, Lists
, Multimaps
, Multisets
, Ranges
Upvotes: 16
Reputation: 533660
Persoanlly I find it easier to read, but it is entirely down to taste.
The main con is when the equals()
for a class does a
if (getClass() != ThisClass.class) return false;
The anonynous class is a sub-class and can break the equals()
method depending on how it has been implemented.
Upvotes: 1
Reputation: 19702
It is much more difficult to read this way, especially with the {{ and }}.
Upvotes: 2