• Post Reply Bookmark Topic Watch Topic
  • New Topic

Meaning of double curly brace in Set  RSS feed

 
Maria Kowalczyk
Greenhorn
Posts: 15
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. I saw code like this.

I can understand that it is a HashSet with one element "Hello" in it.
I don't understand this syntax. Why there are double curly braces?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maria Kowalczyk wrote:

I can understand that it is a HashSet with one element "Hello" in it.
I don't understand this syntax. Why there are double curly braces?



It is a pretty weird piece of code. The outer set of curly braces is part of the anonymous inner class. And the inner set of braces is an instance initializer.

Basically, the code is subclassing the HashSet class, in order to create a set with the "Hello" string loaded.

Henry
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maria Kowalczyk wrote:
I don't understand this syntax. Why there are double curly braces?

This way of initialization is called - Double Braces Initialization. It consists of an anonymous class declaration, along with an instance initializer block directly following. You would hardly use them in real code. It just makes the code harder to read, and in fact un-understandable for the ones who don't know about it. Rather you can just add the "Hello" string later on.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maria Kowalczyk wrote:I don't understand this syntax...

Partly because of the way it's presented (and unfortunately, it often is shown that way in books). If you'd seen it with proper indenting, viz:I suspect you might have worked the mechanics out more easily.

While I agree with the others that arcane code like this is usually best avoided, it's possibly worth pointing out that the idiom can also be used to initialize many extendable classes with non-trivial set-ups, eg:However, as with most things in programming, there are other alternatives (eg, for the above example, a Builder); and the idiom does have other 'gotchas' that are worth knowing about, some of which are detailed here.

Basically, it's a Java curio, but kind of a fun one - and not the worst of its kind.

For example, one place I could see it being of use would be for initializing lookup tables, eg:because it's quite "visual".

HIH

Winston
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!