TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Java Hack: Double Brace Initialization

37 点作者 smokestack将近 16 年前

6 条评论

ZitchDog将近 16 年前
Watch out - double-brace initialization is cool looking, but it's orders of magnitude slower than regular initialization as it must generate an anonymous class.<p>Also, the generated class is put into the permgen space, which is not garbage collected. The permgen is pretty small by default - and if you fill it up, your system is hosed.<p>I use them all the time in unit tests, but never in production code.
评论 #708871 未加载
评论 #708807 未加载
评论 #709220 未加载
评论 #709515 未加载
评论 #709668 未加载
评论 #709172 未加载
评论 #709171 未加载
fi0660将近 16 年前
For initializing lists there is a less verbose expression in Java:<p><pre><code> List&#60;Integer&#62; list = Arrays.asList(1,2,3,4,5);</code></pre>
评论 #709374 未加载
duncanj将近 16 年前
Nice. Could have used that thought about 9 years ago :)
codahale将近 16 年前
This is where Google Collections comes in handy:<p><pre><code> Lists.newArrayList(1, 2, 3) </code></pre> Or, if you don't need to modify it:<p><pre><code> ImmutableList.of(1, 2, 3) </code></pre> Such an awesome library.
eldenbishop将近 16 年前
I've been using this for years. It is a fantastic way to build up hierarchies. XML, maps, JSON, UI code etc. It is very concise, fast and produces clean code which also just happens to correctly indent when you apply code formatting.<p><pre><code> School s = new School() {{ add(new Student() {{ name = "Bobby"; age = 15; add(new Pet() {{ name = "Fluffy"; }}); }}); }}; vs. School sc = new School(); Student st = new Student(); st.name = "Bobby"; st.age = 15; Pet p = new Pet(); p.name = "Fluffy"; st.add(p); sc.add(st);</code></pre>
eldenbishop将近 16 年前
One thing though. I love this technique but the home built Eclipse compiler is not fully Java language compliant and it will reject certain forms of this as invalid. Specifically, the sun and eclipse compiler treat "this" differently in these code blocks. My project will not compile under eclipse because of certain usages of this pattern when combined with inner classes. The bug crops up when you need to pass the parent to the child object being initialized in the static block.