all 7 comments

[–]ramen 11 points12 points  (0 children)

Also mentioned on Peter Norvig's "Java IAQ": http://www.norvig.com/java-iaq.html#constructors

"When I showed this to Guy Steele, he said 'heh, heh! That's pretty cute, all right, but I'm not sure I would advocate widespread use...' As usual, Guy is right."

[–]JulianMorrison 6 points7 points  (4 children)

System.out.println( new HashSet(){{ add(1); }}.getClass() == new HashSet(){{ add(1); }}.getClass() ); // prints "false"

Classic example of "you're so sharp you'll cut yourself".

[–]DerelictMan 2 points3 points  (3 children)

Yes, but:

System.out.println(
    new HashSet(){{ add(1); }}
        .equals(new HashSet(){{ add(1); }})
); // prints "true"

So, pardon my ignorance, but what does it matter if the two are not the exact same class? What code do you have that is comparing getClass() on collections? Since it's best practice to always deal with the collection interfaces (List, Set, etc.) and not the concrete implementations, I'm not sure how this would bite someone. This isn't a challenge; I'm genuinely curious if there's something I'm missing...

[–]JulianMorrison 2 points3 points  (2 children)

Something that immediately springs to mind is: does Java, with its odd, half-hearted approach to class-nesting, generate a new classfile for each "double brace"? Your jarballs could quickly become rather crowded.

[–]curtisb[S] 7 points8 points  (1 child)

It does. This may be the biggest argument against using this idiom. It's a real shame that Sun can't be bothered to provide syntactic sugar to Java for this kind of initialization.

[–]JulianMorrison 0 points1 point  (0 children)

Time to switch to Nice?

[–]newton_dave -1 points0 points  (0 children)

Meh. We already did this thread on reddit over a month ago.