In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax:
Set flavors = new HashSet
leak prone
I've decided to chime in. The performance impact includes: disk operation + unzip (for jar), class verification, perm-gen space (for Sun's Hotspot JVM). However, worst of all: it's leak prone. You can't simply return.
Set getFlavors(){
return Collections.unmodifiableSet(flavors)
}
So if the set escapes to any other part loaded by a different classloader and a reference is kept there, the entire tree of classes+classloader will be leaked. To avoid that, a copy to HashMap is necessary, new LinkedHashSet(new ArrayList(){{add("xxx);add("yyy");}})
. Not so cute any more.
I don't use the idiom, myself, instead it is like new LinkedHashSet(Arrays.asList("xxx","YYY"));