What is Double Brace initialization in Java?
What is Double Brace initialization syntax ({{ ... }}
) in Java?
java initialization double-brace-initialize
add a comment |
What is Double Brace initialization syntax ({{ ... }}
) in Java?
java initialization double-brace-initialize
2
See stackoverflow.com/questions/1372113/…
– skaffman
Dec 24 '09 at 15:09
2
See also stackoverflow.com/q/924285/45935
– Jim Ferrans
May 21 '11 at 21:52
10
Double Brace initialization is a very dangerous feature and should be used judiciously. It may break equals contract and introduce tricky memory leaks. This article describes the details.
– Andrii Polunin
Dec 25 '12 at 10:42
1
It apparently also kills wee kittens ;) stackoverflow.com/a/27521360/1678392
– skia.heliou
Dec 20 '16 at 17:32
add a comment |
What is Double Brace initialization syntax ({{ ... }}
) in Java?
java initialization double-brace-initialize
What is Double Brace initialization syntax ({{ ... }}
) in Java?
java initialization double-brace-initialize
java initialization double-brace-initialize
edited Jun 1 '16 at 10:48
Andrew Tobilko
28.4k104589
28.4k104589
asked Dec 24 '09 at 15:06
sgokhalessgokhales
35.9k26107140
35.9k26107140
2
See stackoverflow.com/questions/1372113/…
– skaffman
Dec 24 '09 at 15:09
2
See also stackoverflow.com/q/924285/45935
– Jim Ferrans
May 21 '11 at 21:52
10
Double Brace initialization is a very dangerous feature and should be used judiciously. It may break equals contract and introduce tricky memory leaks. This article describes the details.
– Andrii Polunin
Dec 25 '12 at 10:42
1
It apparently also kills wee kittens ;) stackoverflow.com/a/27521360/1678392
– skia.heliou
Dec 20 '16 at 17:32
add a comment |
2
See stackoverflow.com/questions/1372113/…
– skaffman
Dec 24 '09 at 15:09
2
See also stackoverflow.com/q/924285/45935
– Jim Ferrans
May 21 '11 at 21:52
10
Double Brace initialization is a very dangerous feature and should be used judiciously. It may break equals contract and introduce tricky memory leaks. This article describes the details.
– Andrii Polunin
Dec 25 '12 at 10:42
1
It apparently also kills wee kittens ;) stackoverflow.com/a/27521360/1678392
– skia.heliou
Dec 20 '16 at 17:32
2
2
See stackoverflow.com/questions/1372113/…
– skaffman
Dec 24 '09 at 15:09
See stackoverflow.com/questions/1372113/…
– skaffman
Dec 24 '09 at 15:09
2
2
See also stackoverflow.com/q/924285/45935
– Jim Ferrans
May 21 '11 at 21:52
See also stackoverflow.com/q/924285/45935
– Jim Ferrans
May 21 '11 at 21:52
10
10
Double Brace initialization is a very dangerous feature and should be used judiciously. It may break equals contract and introduce tricky memory leaks. This article describes the details.
– Andrii Polunin
Dec 25 '12 at 10:42
Double Brace initialization is a very dangerous feature and should be used judiciously. It may break equals contract and introduce tricky memory leaks. This article describes the details.
– Andrii Polunin
Dec 25 '12 at 10:42
1
1
It apparently also kills wee kittens ;) stackoverflow.com/a/27521360/1678392
– skia.heliou
Dec 20 '16 at 17:32
It apparently also kills wee kittens ;) stackoverflow.com/a/27521360/1678392
– skia.heliou
Dec 20 '16 at 17:32
add a comment |
13 Answers
13
active
oldest
votes
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this
pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
9
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
3
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
9
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
add a comment |
Every time someone uses double brace initialisation, a kitten gets killed.
Apart from the syntax being rather unusual and not really idiomatic (taste is debatable, of course), you are unnecessarily creating two significant problems in your application, which I've just recently blogged about in more detail here.
1. You're creating way too many anonymous classes
Each time you use double brace initialisation a new class is made. E.g. this example:
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
... will produce these classes:
Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class
That's quite a bit of overhead for your classloader - for nothing! Of course it won't take much initialisation time if you do it once. But if you do this 20'000 times throughout your enterprise application... all that heap memory just for a bit of "syntax sugar"?
2. You're potentially creating a memory leak!
If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected. Consider the following example:
public class ReallyHeavyObject {
// Just to illustrate...
private int tonsOfValues;
private Resource tonsOfResources;
// This method almost does nothing
public Map quickHarmlessMethod() {
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
return source;
}
}
The returned Map
will now contain a reference to the enclosing instance of ReallyHeavyObject
. You probably don't want to risk that:
Image from http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/
3. You can pretend that Java has map literals
To answer your actual question, people have been using this syntax to pretend that Java has something like map literals, similar to the existing array literals:
String array = { "John", "Doe" };
Map map = new HashMap() {{ put("John", "Doe"); }};
Some people may find this syntactically stimulating.
8
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
2
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with{{...}}
and declared as astatic
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?
– lorenzo-s
Dec 2 '16 at 10:05
7
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finallyMap.of()
for that purpose, so that'll be a better solution
– Lukas Eder
Dec 2 '16 at 13:30
1
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly toReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.
– Holger
Jul 12 '18 at 15:30
add a comment |
- The first brace creates a new Anonymous Inner Class.
- The second set of brace creates an instance initializers like static block in Class.
For example:
public class TestHashMap {
public static void main(String args) {
HashMap<String,String> map = new HashMap<String,String>(){
{
put("1", "ONE");
}{
put("2", "TWO");
}{
put("3", "THREE");
}
};
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(string+" ->"+map.get(string));
}
}
}
How it works
First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.
And Second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.
more
add a comment |
For a fun application of double brace initialization, see here Dwemthy’s Array in Java.
An excerpt
private static class IndustrialRaverMonkey
extends Creature.Base {{
life = 46;
strength = 35;
charisma = 91;
weapon = 2;
}}
private static class DwarvenAngel
extends Creature.Base {{
life = 540;
strength = 6;
charisma = 144;
weapon = 50;
}}
And now, be prepared for the BattleOfGrottoOfSausageSmells
and … chunky bacon!
add a comment |
I think it's important to stress that there is no such thing as "Double Brace initialization" in Java. Oracle web-site doesn't have this term. In this example there are two features used together: anonymous class and initializer block. Seems like the old initializer block has been forgotten by developers and cause some confusion in this topic. Citation from Oracle docs:
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
add a comment |
To avoid all negative effects of double brace initialization, such as:
- Broken "equals" compatibility.
- No checks performed, when use direct assignments.
- Possible memory leaks.
do next things:
- Make separate "Builder" class especially for double brace initialization.
- Declare fields with default values.
- Put object creation method in that class.
Example:
public class MyClass {
public static class Builder {
public int first = -1 ;
public double second = Double.NaN;
public String third = null ;
public MyClass create() {
return new MyClass(first, second, third);
}
}
protected final int first ;
protected final double second;
protected final String third ;
protected MyClass(
int first ,
double second,
String third
) {
this.first = first ;
this.second= second;
this.third = third ;
}
public int first () { return first ; }
public double second() { return second; }
public String third () { return third ; }
}
Usage:
MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
Advantages:
- Simply to use.
- Do not breaks "equals" compatibility.
- You can perform checks in creation method.
- No memory leaks.
Disadvantages:
- None.
And, as a result, we have simplest java builder pattern ever.
See all samples at github: java-sf-builder-simple-example
add a comment |
1- There is no such thing as double braces:
I'd like to point out that there is no such thing as double brace initialization. There is only normal traditional one brace initializaition block. Second braces block has nothing to do with initialization. Answers say that those two braces initialize something, but it is not like that.
2- It's not just about anonymous classes but all classes:
Almost all answers talk that it is a thing used when creating anonymous inner classes. I think that people reading those answers will get the impression that this is only used when creating anonymous inner classes. But it is used in all classes. Reading those answers it looks like is some brand new special feature dedicated to anonymous classes and I think that is misleading.
3- The purpose is just about placing brackets after each other, not new concept:
Going further, this question talks about situation when second opening bracket is just after first opening bracket. When used in normal class usually there is some code between two braces, but it is totally the same thing. So it is a matter of placing brackets. So I think we should not say that this is some new exciting thing, because this is the thing which we all know, but just written with some code between brackets. We should not create new concept called "double brace initialization".
4- Creating nested anonymous classes has nothing to do with two braces:
I don't agree with an argument that you create too many anonymous classes. You're not creating them because an initialization block, but just because you create them. They would be created even if you did not use two braces initialization so those problems would occur even without initialization... Initialization is not the factor which creates initialized objects.
Additionally we should not talk about problem created by using this non-existent thing "double brace initialization" or even by normal one bracket initialization, because described problems exist only because of creating anonymous class so it has nothing to do with original question. But all answers with give the readers impression that it is not fault of creating anonymous classes, but this evil (non-existent) thing called "double brace initialization".
add a comment |
It's - among other uses - a shortcut for initializing collections. Learn more ...
2
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
add a comment |
you mean something like this?
List<String> blah = new ArrayList<String>(){{add("asdfa");add("bbb");}};
it's an array list initialization in creation time (hack)
add a comment |
You can put some Java statements as loop to initialize collection:
List<Character> characters = new ArrayList<Character>() {
{
for (char c = 'A'; c <= 'E'; c++) add(c);
}
};
Random rnd = new Random();
List<Integer> integers = new ArrayList<Integer>() {
{
while (size() < 10) add(rnd.nextInt(1_000_000));
}
};
But this case affect to performance, check this discussion
add a comment |
Double brace initialization takes advantage of the inner class syntax. Suppose you want to construct an array list and pass it to a method:
ArrayList<String> friends = new ArrayList<>();
friends.add("Mark");
friends.add("Steve");
invite(friends);
If you don't need the array list again, it would be nice to make it anonymous. But then how can you add the elements? (double brace initialization comes here) Here is how:
invite(new ArrayList<String>({{ add("Mark"); add("Steve");}});
Note the double braces. The outer braces make an anonymous subclass of ArrayList
. The inner braces are an object construction block.
add a comment |
This would appear to be the same as the with keyword so popular in flash and vbscript. It's a method of changing what this
is and nothing more.
Not really. That would be like saying creating a new class is a method for changing whatthis
is. The syntax just creates an anonymous class (so any reference tothis
would be referring to the object of that new anonymous class), and then uses an initializer block{...}
in order to initialize the newly created instance.
– grinch
Jun 19 '13 at 20:58
add a comment |
As pointed out by @Lukas Eder double braces initialization of collections must be avoided.
It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.
Java 9 has introduced convenience methods List.of
, Set.of
, and Map.of
, which should be used instead. They're faster and more efficient than the double-brace initializer.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1958636%2fwhat-is-double-brace-initialization-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this
pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
9
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
3
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
9
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
add a comment |
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this
pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
9
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
3
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
9
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
add a comment |
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this
pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this
pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
edited Jun 2 '15 at 9:07
answered Dec 24 '09 at 16:40
Brian AgnewBrian Agnew
230k32283398
230k32283398
9
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
3
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
9
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
add a comment |
9
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
3
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
9
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
9
9
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
Thanks for clarifying the meaning of the inner and outer braces. I've wondered why there are suddenly two braces allowed with a special meaning, when they are in fact normal java constructs that only appear as some magical new trick. Things like that make me question Java syntax though. If you're not an expert already it can be very tricky to read and write.
– jackthehipster
Jul 9 '14 at 11:53
3
3
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
"Magic syntax" like this exists in many languages, for example almost all C-like languages support the "goes to 0" syntax of "x --> 0" in for loops which is just "x-- > 0" with weird space placement.
– Joachim Sauer
Jan 5 '18 at 12:03
9
9
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
We can just conclude that "double brace initialization" does not exist on its own, it is just a combination of creating an anonymous class and an initializer block, which, once combined, looks like a syntactical construct, but in reality, it isn't.
– MC Emperor
Jan 5 '18 at 13:55
add a comment |
Every time someone uses double brace initialisation, a kitten gets killed.
Apart from the syntax being rather unusual and not really idiomatic (taste is debatable, of course), you are unnecessarily creating two significant problems in your application, which I've just recently blogged about in more detail here.
1. You're creating way too many anonymous classes
Each time you use double brace initialisation a new class is made. E.g. this example:
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
... will produce these classes:
Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class
That's quite a bit of overhead for your classloader - for nothing! Of course it won't take much initialisation time if you do it once. But if you do this 20'000 times throughout your enterprise application... all that heap memory just for a bit of "syntax sugar"?
2. You're potentially creating a memory leak!
If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected. Consider the following example:
public class ReallyHeavyObject {
// Just to illustrate...
private int tonsOfValues;
private Resource tonsOfResources;
// This method almost does nothing
public Map quickHarmlessMethod() {
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
return source;
}
}
The returned Map
will now contain a reference to the enclosing instance of ReallyHeavyObject
. You probably don't want to risk that:
Image from http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/
3. You can pretend that Java has map literals
To answer your actual question, people have been using this syntax to pretend that Java has something like map literals, similar to the existing array literals:
String array = { "John", "Doe" };
Map map = new HashMap() {{ put("John", "Doe"); }};
Some people may find this syntactically stimulating.
8
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
2
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with{{...}}
and declared as astatic
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?
– lorenzo-s
Dec 2 '16 at 10:05
7
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finallyMap.of()
for that purpose, so that'll be a better solution
– Lukas Eder
Dec 2 '16 at 13:30
1
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly toReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.
– Holger
Jul 12 '18 at 15:30
add a comment |
Every time someone uses double brace initialisation, a kitten gets killed.
Apart from the syntax being rather unusual and not really idiomatic (taste is debatable, of course), you are unnecessarily creating two significant problems in your application, which I've just recently blogged about in more detail here.
1. You're creating way too many anonymous classes
Each time you use double brace initialisation a new class is made. E.g. this example:
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
... will produce these classes:
Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class
That's quite a bit of overhead for your classloader - for nothing! Of course it won't take much initialisation time if you do it once. But if you do this 20'000 times throughout your enterprise application... all that heap memory just for a bit of "syntax sugar"?
2. You're potentially creating a memory leak!
If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected. Consider the following example:
public class ReallyHeavyObject {
// Just to illustrate...
private int tonsOfValues;
private Resource tonsOfResources;
// This method almost does nothing
public Map quickHarmlessMethod() {
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
return source;
}
}
The returned Map
will now contain a reference to the enclosing instance of ReallyHeavyObject
. You probably don't want to risk that:
Image from http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/
3. You can pretend that Java has map literals
To answer your actual question, people have been using this syntax to pretend that Java has something like map literals, similar to the existing array literals:
String array = { "John", "Doe" };
Map map = new HashMap() {{ put("John", "Doe"); }};
Some people may find this syntactically stimulating.
8
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
2
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with{{...}}
and declared as astatic
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?
– lorenzo-s
Dec 2 '16 at 10:05
7
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finallyMap.of()
for that purpose, so that'll be a better solution
– Lukas Eder
Dec 2 '16 at 13:30
1
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly toReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.
– Holger
Jul 12 '18 at 15:30
add a comment |
Every time someone uses double brace initialisation, a kitten gets killed.
Apart from the syntax being rather unusual and not really idiomatic (taste is debatable, of course), you are unnecessarily creating two significant problems in your application, which I've just recently blogged about in more detail here.
1. You're creating way too many anonymous classes
Each time you use double brace initialisation a new class is made. E.g. this example:
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
... will produce these classes:
Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class
That's quite a bit of overhead for your classloader - for nothing! Of course it won't take much initialisation time if you do it once. But if you do this 20'000 times throughout your enterprise application... all that heap memory just for a bit of "syntax sugar"?
2. You're potentially creating a memory leak!
If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected. Consider the following example:
public class ReallyHeavyObject {
// Just to illustrate...
private int tonsOfValues;
private Resource tonsOfResources;
// This method almost does nothing
public Map quickHarmlessMethod() {
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
return source;
}
}
The returned Map
will now contain a reference to the enclosing instance of ReallyHeavyObject
. You probably don't want to risk that:
Image from http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/
3. You can pretend that Java has map literals
To answer your actual question, people have been using this syntax to pretend that Java has something like map literals, similar to the existing array literals:
String array = { "John", "Doe" };
Map map = new HashMap() {{ put("John", "Doe"); }};
Some people may find this syntactically stimulating.
Every time someone uses double brace initialisation, a kitten gets killed.
Apart from the syntax being rather unusual and not really idiomatic (taste is debatable, of course), you are unnecessarily creating two significant problems in your application, which I've just recently blogged about in more detail here.
1. You're creating way too many anonymous classes
Each time you use double brace initialisation a new class is made. E.g. this example:
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
... will produce these classes:
Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class
That's quite a bit of overhead for your classloader - for nothing! Of course it won't take much initialisation time if you do it once. But if you do this 20'000 times throughout your enterprise application... all that heap memory just for a bit of "syntax sugar"?
2. You're potentially creating a memory leak!
If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected. Consider the following example:
public class ReallyHeavyObject {
// Just to illustrate...
private int tonsOfValues;
private Resource tonsOfResources;
// This method almost does nothing
public Map quickHarmlessMethod() {
Map source = new HashMap(){{
put("firstName", "John");
put("lastName", "Smith");
put("organizations", new HashMap(){{
put("0", new HashMap(){{
put("id", "1234");
}});
put("abc", new HashMap(){{
put("id", "5678");
}});
}});
}};
return source;
}
}
The returned Map
will now contain a reference to the enclosing instance of ReallyHeavyObject
. You probably don't want to risk that:
Image from http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/
3. You can pretend that Java has map literals
To answer your actual question, people have been using this syntax to pretend that Java has something like map literals, similar to the existing array literals:
String array = { "John", "Doe" };
Map map = new HashMap() {{ put("John", "Doe"); }};
Some people may find this syntactically stimulating.
edited Dec 17 '14 at 8:53
answered Dec 17 '14 at 8:41
Lukas EderLukas Eder
136k73444974
136k73444974
8
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
2
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with{{...}}
and declared as astatic
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?
– lorenzo-s
Dec 2 '16 at 10:05
7
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finallyMap.of()
for that purpose, so that'll be a better solution
– Lukas Eder
Dec 2 '16 at 13:30
1
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly toReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.
– Holger
Jul 12 '18 at 15:30
add a comment |
8
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
2
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with{{...}}
and declared as astatic
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?
– lorenzo-s
Dec 2 '16 at 10:05
7
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finallyMap.of()
for that purpose, so that'll be a better solution
– Lukas Eder
Dec 2 '16 at 13:30
1
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly toReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.
– Holger
Jul 12 '18 at 15:30
8
8
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
"You're creating way too many anonymous classes" - looking at how (say) Scala creates anonymous classes, I'm not too sure that this is a major problem
– Brian Agnew
Jan 26 '16 at 12:07
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
@BrianAgnew: It depends on the context of course.
– Lukas Eder
Jan 26 '16 at 12:30
2
2
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with
{{...}}
and declared as a static
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?– lorenzo-s
Dec 2 '16 at 10:05
Doesn't it remains a valid and nice way to declare static maps? If an HashMap is initialized with
{{...}}
and declared as a static
field, there shouldn't be any possible memory leak, only one anonymous class and no enclosed instance references, right?– lorenzo-s
Dec 2 '16 at 10:05
7
7
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finally
Map.of()
for that purpose, so that'll be a better solution– Lukas Eder
Dec 2 '16 at 13:30
@lorenzo-s: Yes, 2) and 3) don't apply then, only 1). Luckily, with Java 9, there's finally
Map.of()
for that purpose, so that'll be a better solution– Lukas Eder
Dec 2 '16 at 13:30
1
1
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly to
ReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.– Holger
Jul 12 '18 at 15:30
It might be worth noting that the inner maps also have references to the outer maps and hence, indirectly to
ReallyHeavyObject
. Also, anonymous inner classes capture all local variables used within the class body, so if you use not only constants to initialize collections or maps with this pattern, the inner class instances will capture all of them and continue to reference them even when actually removed from the collection or map. So it that case, these instances do not only need twice as necessary memory for the references, but have another memory leak in that regard.– Holger
Jul 12 '18 at 15:30
add a comment |
- The first brace creates a new Anonymous Inner Class.
- The second set of brace creates an instance initializers like static block in Class.
For example:
public class TestHashMap {
public static void main(String args) {
HashMap<String,String> map = new HashMap<String,String>(){
{
put("1", "ONE");
}{
put("2", "TWO");
}{
put("3", "THREE");
}
};
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(string+" ->"+map.get(string));
}
}
}
How it works
First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.
And Second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.
more
add a comment |
- The first brace creates a new Anonymous Inner Class.
- The second set of brace creates an instance initializers like static block in Class.
For example:
public class TestHashMap {
public static void main(String args) {
HashMap<String,String> map = new HashMap<String,String>(){
{
put("1", "ONE");
}{
put("2", "TWO");
}{
put("3", "THREE");
}
};
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(string+" ->"+map.get(string));
}
}
}
How it works
First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.
And Second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.
more
add a comment |
- The first brace creates a new Anonymous Inner Class.
- The second set of brace creates an instance initializers like static block in Class.
For example:
public class TestHashMap {
public static void main(String args) {
HashMap<String,String> map = new HashMap<String,String>(){
{
put("1", "ONE");
}{
put("2", "TWO");
}{
put("3", "THREE");
}
};
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(string+" ->"+map.get(string));
}
}
}
How it works
First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.
And Second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.
more
- The first brace creates a new Anonymous Inner Class.
- The second set of brace creates an instance initializers like static block in Class.
For example:
public class TestHashMap {
public static void main(String args) {
HashMap<String,String> map = new HashMap<String,String>(){
{
put("1", "ONE");
}{
put("2", "TWO");
}{
put("3", "THREE");
}
};
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(string+" ->"+map.get(string));
}
}
}
How it works
First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.
And Second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.
more
edited Mar 1 at 12:49
answered Aug 5 '15 at 9:56
PremrajPremraj
31.8k12160119
31.8k12160119
add a comment |
add a comment |
For a fun application of double brace initialization, see here Dwemthy’s Array in Java.
An excerpt
private static class IndustrialRaverMonkey
extends Creature.Base {{
life = 46;
strength = 35;
charisma = 91;
weapon = 2;
}}
private static class DwarvenAngel
extends Creature.Base {{
life = 540;
strength = 6;
charisma = 144;
weapon = 50;
}}
And now, be prepared for the BattleOfGrottoOfSausageSmells
and … chunky bacon!
add a comment |
For a fun application of double brace initialization, see here Dwemthy’s Array in Java.
An excerpt
private static class IndustrialRaverMonkey
extends Creature.Base {{
life = 46;
strength = 35;
charisma = 91;
weapon = 2;
}}
private static class DwarvenAngel
extends Creature.Base {{
life = 540;
strength = 6;
charisma = 144;
weapon = 50;
}}
And now, be prepared for the BattleOfGrottoOfSausageSmells
and … chunky bacon!
add a comment |
For a fun application of double brace initialization, see here Dwemthy’s Array in Java.
An excerpt
private static class IndustrialRaverMonkey
extends Creature.Base {{
life = 46;
strength = 35;
charisma = 91;
weapon = 2;
}}
private static class DwarvenAngel
extends Creature.Base {{
life = 540;
strength = 6;
charisma = 144;
weapon = 50;
}}
And now, be prepared for the BattleOfGrottoOfSausageSmells
and … chunky bacon!
For a fun application of double brace initialization, see here Dwemthy’s Array in Java.
An excerpt
private static class IndustrialRaverMonkey
extends Creature.Base {{
life = 46;
strength = 35;
charisma = 91;
weapon = 2;
}}
private static class DwarvenAngel
extends Creature.Base {{
life = 540;
strength = 6;
charisma = 144;
weapon = 50;
}}
And now, be prepared for the BattleOfGrottoOfSausageSmells
and … chunky bacon!
answered Dec 24 '09 at 16:57
akuhnakuhn
23.2k25777
23.2k25777
add a comment |
add a comment |
I think it's important to stress that there is no such thing as "Double Brace initialization" in Java. Oracle web-site doesn't have this term. In this example there are two features used together: anonymous class and initializer block. Seems like the old initializer block has been forgotten by developers and cause some confusion in this topic. Citation from Oracle docs:
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
add a comment |
I think it's important to stress that there is no such thing as "Double Brace initialization" in Java. Oracle web-site doesn't have this term. In this example there are two features used together: anonymous class and initializer block. Seems like the old initializer block has been forgotten by developers and cause some confusion in this topic. Citation from Oracle docs:
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
add a comment |
I think it's important to stress that there is no such thing as "Double Brace initialization" in Java. Oracle web-site doesn't have this term. In this example there are two features used together: anonymous class and initializer block. Seems like the old initializer block has been forgotten by developers and cause some confusion in this topic. Citation from Oracle docs:
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
I think it's important to stress that there is no such thing as "Double Brace initialization" in Java. Oracle web-site doesn't have this term. In this example there are two features used together: anonymous class and initializer block. Seems like the old initializer block has been forgotten by developers and cause some confusion in this topic. Citation from Oracle docs:
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
answered Dec 20 '16 at 13:18
Alex TAlex T
4501619
4501619
add a comment |
add a comment |
To avoid all negative effects of double brace initialization, such as:
- Broken "equals" compatibility.
- No checks performed, when use direct assignments.
- Possible memory leaks.
do next things:
- Make separate "Builder" class especially for double brace initialization.
- Declare fields with default values.
- Put object creation method in that class.
Example:
public class MyClass {
public static class Builder {
public int first = -1 ;
public double second = Double.NaN;
public String third = null ;
public MyClass create() {
return new MyClass(first, second, third);
}
}
protected final int first ;
protected final double second;
protected final String third ;
protected MyClass(
int first ,
double second,
String third
) {
this.first = first ;
this.second= second;
this.third = third ;
}
public int first () { return first ; }
public double second() { return second; }
public String third () { return third ; }
}
Usage:
MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
Advantages:
- Simply to use.
- Do not breaks "equals" compatibility.
- You can perform checks in creation method.
- No memory leaks.
Disadvantages:
- None.
And, as a result, we have simplest java builder pattern ever.
See all samples at github: java-sf-builder-simple-example
add a comment |
To avoid all negative effects of double brace initialization, such as:
- Broken "equals" compatibility.
- No checks performed, when use direct assignments.
- Possible memory leaks.
do next things:
- Make separate "Builder" class especially for double brace initialization.
- Declare fields with default values.
- Put object creation method in that class.
Example:
public class MyClass {
public static class Builder {
public int first = -1 ;
public double second = Double.NaN;
public String third = null ;
public MyClass create() {
return new MyClass(first, second, third);
}
}
protected final int first ;
protected final double second;
protected final String third ;
protected MyClass(
int first ,
double second,
String third
) {
this.first = first ;
this.second= second;
this.third = third ;
}
public int first () { return first ; }
public double second() { return second; }
public String third () { return third ; }
}
Usage:
MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
Advantages:
- Simply to use.
- Do not breaks "equals" compatibility.
- You can perform checks in creation method.
- No memory leaks.
Disadvantages:
- None.
And, as a result, we have simplest java builder pattern ever.
See all samples at github: java-sf-builder-simple-example
add a comment |
To avoid all negative effects of double brace initialization, such as:
- Broken "equals" compatibility.
- No checks performed, when use direct assignments.
- Possible memory leaks.
do next things:
- Make separate "Builder" class especially for double brace initialization.
- Declare fields with default values.
- Put object creation method in that class.
Example:
public class MyClass {
public static class Builder {
public int first = -1 ;
public double second = Double.NaN;
public String third = null ;
public MyClass create() {
return new MyClass(first, second, third);
}
}
protected final int first ;
protected final double second;
protected final String third ;
protected MyClass(
int first ,
double second,
String third
) {
this.first = first ;
this.second= second;
this.third = third ;
}
public int first () { return first ; }
public double second() { return second; }
public String third () { return third ; }
}
Usage:
MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
Advantages:
- Simply to use.
- Do not breaks "equals" compatibility.
- You can perform checks in creation method.
- No memory leaks.
Disadvantages:
- None.
And, as a result, we have simplest java builder pattern ever.
See all samples at github: java-sf-builder-simple-example
To avoid all negative effects of double brace initialization, such as:
- Broken "equals" compatibility.
- No checks performed, when use direct assignments.
- Possible memory leaks.
do next things:
- Make separate "Builder" class especially for double brace initialization.
- Declare fields with default values.
- Put object creation method in that class.
Example:
public class MyClass {
public static class Builder {
public int first = -1 ;
public double second = Double.NaN;
public String third = null ;
public MyClass create() {
return new MyClass(first, second, third);
}
}
protected final int first ;
protected final double second;
protected final String third ;
protected MyClass(
int first ,
double second,
String third
) {
this.first = first ;
this.second= second;
this.third = third ;
}
public int first () { return first ; }
public double second() { return second; }
public String third () { return third ; }
}
Usage:
MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
Advantages:
- Simply to use.
- Do not breaks "equals" compatibility.
- You can perform checks in creation method.
- No memory leaks.
Disadvantages:
- None.
And, as a result, we have simplest java builder pattern ever.
See all samples at github: java-sf-builder-simple-example
answered Sep 4 '15 at 18:19
Boris PodchezertsevBoris Podchezertsev
7114
7114
add a comment |
add a comment |
1- There is no such thing as double braces:
I'd like to point out that there is no such thing as double brace initialization. There is only normal traditional one brace initializaition block. Second braces block has nothing to do with initialization. Answers say that those two braces initialize something, but it is not like that.
2- It's not just about anonymous classes but all classes:
Almost all answers talk that it is a thing used when creating anonymous inner classes. I think that people reading those answers will get the impression that this is only used when creating anonymous inner classes. But it is used in all classes. Reading those answers it looks like is some brand new special feature dedicated to anonymous classes and I think that is misleading.
3- The purpose is just about placing brackets after each other, not new concept:
Going further, this question talks about situation when second opening bracket is just after first opening bracket. When used in normal class usually there is some code between two braces, but it is totally the same thing. So it is a matter of placing brackets. So I think we should not say that this is some new exciting thing, because this is the thing which we all know, but just written with some code between brackets. We should not create new concept called "double brace initialization".
4- Creating nested anonymous classes has nothing to do with two braces:
I don't agree with an argument that you create too many anonymous classes. You're not creating them because an initialization block, but just because you create them. They would be created even if you did not use two braces initialization so those problems would occur even without initialization... Initialization is not the factor which creates initialized objects.
Additionally we should not talk about problem created by using this non-existent thing "double brace initialization" or even by normal one bracket initialization, because described problems exist only because of creating anonymous class so it has nothing to do with original question. But all answers with give the readers impression that it is not fault of creating anonymous classes, but this evil (non-existent) thing called "double brace initialization".
add a comment |
1- There is no such thing as double braces:
I'd like to point out that there is no such thing as double brace initialization. There is only normal traditional one brace initializaition block. Second braces block has nothing to do with initialization. Answers say that those two braces initialize something, but it is not like that.
2- It's not just about anonymous classes but all classes:
Almost all answers talk that it is a thing used when creating anonymous inner classes. I think that people reading those answers will get the impression that this is only used when creating anonymous inner classes. But it is used in all classes. Reading those answers it looks like is some brand new special feature dedicated to anonymous classes and I think that is misleading.
3- The purpose is just about placing brackets after each other, not new concept:
Going further, this question talks about situation when second opening bracket is just after first opening bracket. When used in normal class usually there is some code between two braces, but it is totally the same thing. So it is a matter of placing brackets. So I think we should not say that this is some new exciting thing, because this is the thing which we all know, but just written with some code between brackets. We should not create new concept called "double brace initialization".
4- Creating nested anonymous classes has nothing to do with two braces:
I don't agree with an argument that you create too many anonymous classes. You're not creating them because an initialization block, but just because you create them. They would be created even if you did not use two braces initialization so those problems would occur even without initialization... Initialization is not the factor which creates initialized objects.
Additionally we should not talk about problem created by using this non-existent thing "double brace initialization" or even by normal one bracket initialization, because described problems exist only because of creating anonymous class so it has nothing to do with original question. But all answers with give the readers impression that it is not fault of creating anonymous classes, but this evil (non-existent) thing called "double brace initialization".
add a comment |
1- There is no such thing as double braces:
I'd like to point out that there is no such thing as double brace initialization. There is only normal traditional one brace initializaition block. Second braces block has nothing to do with initialization. Answers say that those two braces initialize something, but it is not like that.
2- It's not just about anonymous classes but all classes:
Almost all answers talk that it is a thing used when creating anonymous inner classes. I think that people reading those answers will get the impression that this is only used when creating anonymous inner classes. But it is used in all classes. Reading those answers it looks like is some brand new special feature dedicated to anonymous classes and I think that is misleading.
3- The purpose is just about placing brackets after each other, not new concept:
Going further, this question talks about situation when second opening bracket is just after first opening bracket. When used in normal class usually there is some code between two braces, but it is totally the same thing. So it is a matter of placing brackets. So I think we should not say that this is some new exciting thing, because this is the thing which we all know, but just written with some code between brackets. We should not create new concept called "double brace initialization".
4- Creating nested anonymous classes has nothing to do with two braces:
I don't agree with an argument that you create too many anonymous classes. You're not creating them because an initialization block, but just because you create them. They would be created even if you did not use two braces initialization so those problems would occur even without initialization... Initialization is not the factor which creates initialized objects.
Additionally we should not talk about problem created by using this non-existent thing "double brace initialization" or even by normal one bracket initialization, because described problems exist only because of creating anonymous class so it has nothing to do with original question. But all answers with give the readers impression that it is not fault of creating anonymous classes, but this evil (non-existent) thing called "double brace initialization".
1- There is no such thing as double braces:
I'd like to point out that there is no such thing as double brace initialization. There is only normal traditional one brace initializaition block. Second braces block has nothing to do with initialization. Answers say that those two braces initialize something, but it is not like that.
2- It's not just about anonymous classes but all classes:
Almost all answers talk that it is a thing used when creating anonymous inner classes. I think that people reading those answers will get the impression that this is only used when creating anonymous inner classes. But it is used in all classes. Reading those answers it looks like is some brand new special feature dedicated to anonymous classes and I think that is misleading.
3- The purpose is just about placing brackets after each other, not new concept:
Going further, this question talks about situation when second opening bracket is just after first opening bracket. When used in normal class usually there is some code between two braces, but it is totally the same thing. So it is a matter of placing brackets. So I think we should not say that this is some new exciting thing, because this is the thing which we all know, but just written with some code between brackets. We should not create new concept called "double brace initialization".
4- Creating nested anonymous classes has nothing to do with two braces:
I don't agree with an argument that you create too many anonymous classes. You're not creating them because an initialization block, but just because you create them. They would be created even if you did not use two braces initialization so those problems would occur even without initialization... Initialization is not the factor which creates initialized objects.
Additionally we should not talk about problem created by using this non-existent thing "double brace initialization" or even by normal one bracket initialization, because described problems exist only because of creating anonymous class so it has nothing to do with original question. But all answers with give the readers impression that it is not fault of creating anonymous classes, but this evil (non-existent) thing called "double brace initialization".
edited Feb 24 at 17:29
Pete
47758
47758
answered Nov 28 '15 at 19:04
ctomekctomek
9991020
9991020
add a comment |
add a comment |
It's - among other uses - a shortcut for initializing collections. Learn more ...
2
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
add a comment |
It's - among other uses - a shortcut for initializing collections. Learn more ...
2
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
add a comment |
It's - among other uses - a shortcut for initializing collections. Learn more ...
It's - among other uses - a shortcut for initializing collections. Learn more ...
edited Dec 24 '09 at 15:14
answered Dec 24 '09 at 15:08
mikumiku
131k35248275
131k35248275
2
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
add a comment |
2
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
2
2
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
Well, that's one application for it, but by no means the only one.
– skaffman
Dec 24 '09 at 15:12
add a comment |
you mean something like this?
List<String> blah = new ArrayList<String>(){{add("asdfa");add("bbb");}};
it's an array list initialization in creation time (hack)
add a comment |
you mean something like this?
List<String> blah = new ArrayList<String>(){{add("asdfa");add("bbb");}};
it's an array list initialization in creation time (hack)
add a comment |
you mean something like this?
List<String> blah = new ArrayList<String>(){{add("asdfa");add("bbb");}};
it's an array list initialization in creation time (hack)
you mean something like this?
List<String> blah = new ArrayList<String>(){{add("asdfa");add("bbb");}};
it's an array list initialization in creation time (hack)
answered Mar 29 '11 at 16:15
dhblahdhblah
4,35083873
4,35083873
add a comment |
add a comment |
You can put some Java statements as loop to initialize collection:
List<Character> characters = new ArrayList<Character>() {
{
for (char c = 'A'; c <= 'E'; c++) add(c);
}
};
Random rnd = new Random();
List<Integer> integers = new ArrayList<Integer>() {
{
while (size() < 10) add(rnd.nextInt(1_000_000));
}
};
But this case affect to performance, check this discussion
add a comment |
You can put some Java statements as loop to initialize collection:
List<Character> characters = new ArrayList<Character>() {
{
for (char c = 'A'; c <= 'E'; c++) add(c);
}
};
Random rnd = new Random();
List<Integer> integers = new ArrayList<Integer>() {
{
while (size() < 10) add(rnd.nextInt(1_000_000));
}
};
But this case affect to performance, check this discussion
add a comment |
You can put some Java statements as loop to initialize collection:
List<Character> characters = new ArrayList<Character>() {
{
for (char c = 'A'; c <= 'E'; c++) add(c);
}
};
Random rnd = new Random();
List<Integer> integers = new ArrayList<Integer>() {
{
while (size() < 10) add(rnd.nextInt(1_000_000));
}
};
But this case affect to performance, check this discussion
You can put some Java statements as loop to initialize collection:
List<Character> characters = new ArrayList<Character>() {
{
for (char c = 'A'; c <= 'E'; c++) add(c);
}
};
Random rnd = new Random();
List<Integer> integers = new ArrayList<Integer>() {
{
while (size() < 10) add(rnd.nextInt(1_000_000));
}
};
But this case affect to performance, check this discussion
edited May 23 '17 at 12:10
Community♦
11
11
answered Jul 20 '14 at 15:46
Anton DozortsevAnton Dozortsev
3,16832658
3,16832658
add a comment |
add a comment |
Double brace initialization takes advantage of the inner class syntax. Suppose you want to construct an array list and pass it to a method:
ArrayList<String> friends = new ArrayList<>();
friends.add("Mark");
friends.add("Steve");
invite(friends);
If you don't need the array list again, it would be nice to make it anonymous. But then how can you add the elements? (double brace initialization comes here) Here is how:
invite(new ArrayList<String>({{ add("Mark"); add("Steve");}});
Note the double braces. The outer braces make an anonymous subclass of ArrayList
. The inner braces are an object construction block.
add a comment |
Double brace initialization takes advantage of the inner class syntax. Suppose you want to construct an array list and pass it to a method:
ArrayList<String> friends = new ArrayList<>();
friends.add("Mark");
friends.add("Steve");
invite(friends);
If you don't need the array list again, it would be nice to make it anonymous. But then how can you add the elements? (double brace initialization comes here) Here is how:
invite(new ArrayList<String>({{ add("Mark"); add("Steve");}});
Note the double braces. The outer braces make an anonymous subclass of ArrayList
. The inner braces are an object construction block.
add a comment |
Double brace initialization takes advantage of the inner class syntax. Suppose you want to construct an array list and pass it to a method:
ArrayList<String> friends = new ArrayList<>();
friends.add("Mark");
friends.add("Steve");
invite(friends);
If you don't need the array list again, it would be nice to make it anonymous. But then how can you add the elements? (double brace initialization comes here) Here is how:
invite(new ArrayList<String>({{ add("Mark"); add("Steve");}});
Note the double braces. The outer braces make an anonymous subclass of ArrayList
. The inner braces are an object construction block.
Double brace initialization takes advantage of the inner class syntax. Suppose you want to construct an array list and pass it to a method:
ArrayList<String> friends = new ArrayList<>();
friends.add("Mark");
friends.add("Steve");
invite(friends);
If you don't need the array list again, it would be nice to make it anonymous. But then how can you add the elements? (double brace initialization comes here) Here is how:
invite(new ArrayList<String>({{ add("Mark"); add("Steve");}});
Note the double braces. The outer braces make an anonymous subclass of ArrayList
. The inner braces are an object construction block.
answered Oct 15 '18 at 16:40
hamza belmelloukihamza belmellouki
151111
151111
add a comment |
add a comment |
This would appear to be the same as the with keyword so popular in flash and vbscript. It's a method of changing what this
is and nothing more.
Not really. That would be like saying creating a new class is a method for changing whatthis
is. The syntax just creates an anonymous class (so any reference tothis
would be referring to the object of that new anonymous class), and then uses an initializer block{...}
in order to initialize the newly created instance.
– grinch
Jun 19 '13 at 20:58
add a comment |
This would appear to be the same as the with keyword so popular in flash and vbscript. It's a method of changing what this
is and nothing more.
Not really. That would be like saying creating a new class is a method for changing whatthis
is. The syntax just creates an anonymous class (so any reference tothis
would be referring to the object of that new anonymous class), and then uses an initializer block{...}
in order to initialize the newly created instance.
– grinch
Jun 19 '13 at 20:58
add a comment |
This would appear to be the same as the with keyword so popular in flash and vbscript. It's a method of changing what this
is and nothing more.
This would appear to be the same as the with keyword so popular in flash and vbscript. It's a method of changing what this
is and nothing more.
answered Dec 24 '09 at 16:56
Chuck VoseChuck Vose
4,1171829
4,1171829
Not really. That would be like saying creating a new class is a method for changing whatthis
is. The syntax just creates an anonymous class (so any reference tothis
would be referring to the object of that new anonymous class), and then uses an initializer block{...}
in order to initialize the newly created instance.
– grinch
Jun 19 '13 at 20:58
add a comment |
Not really. That would be like saying creating a new class is a method for changing whatthis
is. The syntax just creates an anonymous class (so any reference tothis
would be referring to the object of that new anonymous class), and then uses an initializer block{...}
in order to initialize the newly created instance.
– grinch
Jun 19 '13 at 20:58
Not really. That would be like saying creating a new class is a method for changing what
this
is. The syntax just creates an anonymous class (so any reference to this
would be referring to the object of that new anonymous class), and then uses an initializer block {...}
in order to initialize the newly created instance.– grinch
Jun 19 '13 at 20:58
Not really. That would be like saying creating a new class is a method for changing what
this
is. The syntax just creates an anonymous class (so any reference to this
would be referring to the object of that new anonymous class), and then uses an initializer block {...}
in order to initialize the newly created instance.– grinch
Jun 19 '13 at 20:58
add a comment |
As pointed out by @Lukas Eder double braces initialization of collections must be avoided.
It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.
Java 9 has introduced convenience methods List.of
, Set.of
, and Map.of
, which should be used instead. They're faster and more efficient than the double-brace initializer.
add a comment |
As pointed out by @Lukas Eder double braces initialization of collections must be avoided.
It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.
Java 9 has introduced convenience methods List.of
, Set.of
, and Map.of
, which should be used instead. They're faster and more efficient than the double-brace initializer.
add a comment |
As pointed out by @Lukas Eder double braces initialization of collections must be avoided.
It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.
Java 9 has introduced convenience methods List.of
, Set.of
, and Map.of
, which should be used instead. They're faster and more efficient than the double-brace initializer.
As pointed out by @Lukas Eder double braces initialization of collections must be avoided.
It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.
Java 9 has introduced convenience methods List.of
, Set.of
, and Map.of
, which should be used instead. They're faster and more efficient than the double-brace initializer.
answered Oct 29 '18 at 19:39
Mikhail KholodkovMikhail Kholodkov
5,14152951
5,14152951
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1958636%2fwhat-is-double-brace-initialization-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
See stackoverflow.com/questions/1372113/…
– skaffman
Dec 24 '09 at 15:09
2
See also stackoverflow.com/q/924285/45935
– Jim Ferrans
May 21 '11 at 21:52
10
Double Brace initialization is a very dangerous feature and should be used judiciously. It may break equals contract and introduce tricky memory leaks. This article describes the details.
– Andrii Polunin
Dec 25 '12 at 10:42
1
It apparently also kills wee kittens ;) stackoverflow.com/a/27521360/1678392
– skia.heliou
Dec 20 '16 at 17:32