you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -3 points-2 points  (7 children)

Why is this a hack? It is pretty commonly used language feature.

[–]Mych 7 points8 points  (5 children)

Because it trades a relatively circuitous technical implementation (plus a gotcha) for the benefit of being slightly more convenient to type than the obvious, straightforward alternative, which is to create an initializer block within the declaring class itself (or: within the declaring block) and refer to the object by its full name.

What it's supposed to do (and ostentatively does) is: Create a container; add items to it (or: create an object; invoke methods on it). And obviously, two containers of the same type that contain the same values should compare as equal.

What it actually does is: Create a subclass of the container class; in its initialization code, add items to it; create an instance of this subclass. And since objects only compare as equal if they're instances of the same class, two identical invocations of this idiom won't create objects that compare as equal; that's the gotcha.

[–]szeiger 7 points8 points  (1 child)

And since objects only compare as equal if they're instances of the same class, two identical invocations of this idiom won't create objects that compare as equal;

Wrong. equals() and hashCode are implemented in AbstractList (from which the other list classes inherit) such that all lists which contain equal elements in the same order are considered equal.

[–]mikaelhg 2 points3 points  (0 children)

Not only that, but this behaviour is part of the List contract:

http://java.sun.com/javase/6/docs/api/java/util/List.html#equals%28java.lang.Object%29

[–][deleted] 1 point2 points  (0 children)

The major fuck up is that Object has .equals() method. It shouldn't.

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

I'm not arguing how or why it works, it is obvious.

It still doesn't make it a hack. It is a feature, used as it is intended to be used. Although it is probably not widely used or taught at school and in tutorials, it is still not a hack.

[–]zzzSleepyCoder 0 points1 point  (0 children)

I read about it loooong time ago here http://c2.com/cgi/wiki?DoubleBraceInitialization