本文介绍了双支架初始化 - 优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

知道我们可以通过使用双括号初始化在java中初始化一个集合。并进行了一些搜索,发现,不建议使用它,因为它的性能问题。

Got to know that we can initialize a collection in java by using double brace initialization. And did some search on that and found that it is not advised to use it because of its performance issue.

private static final Set<String> VALID_CODES = new HashSet<String>() {{
    add("XZ13s");
    add("AB21/X");
    add("YYLEX");
    add("AR2D");
 }};

只是想知道,DOUBLE BRACE INITIALIZATION是否有积极的一面或优势?

Just want to know, is there any positive side or advantage of DOUBLE BRACE INITIALIZATION??

推荐答案

我没有看到任何性能问题。每当你看到有人说我做的/没有做某事的性能原因,你应该期望看到详细的分析比较替代解释如何满足特定要求的性能,而其他没有。如果你没有看到这一切,你可能会假设作者只是猜测。

I don't see any performance issue. Whenever you see someone say I did/didn't do something for performance reason you should expect to see detailed analysis comparing the alternatives explaining how one met the specific required performance and the other did not. If you don't see all this you might assume the author is just guessing.

编辑:虽然我会承认每个类需要少量的时间加载,运行性能完全一样。我已在此演示

While I will concede each class takes a small amount of time to load, the running performance is exactly the same. I have demonstrated here http://stackoverflow.com/a/14627268/57695

如果你认为它更简单和更清晰,我会使用双括号记号。

I would use double brace notation if you believe it's simpler and clearer.

一个缺点是你正在改变集合的类型,函数,这是不期望的。例如等于。

A disadvantage is that your are changing the type of the collection which can confuse functions where that is not expected. e.g. equals.

注意:正如Lukas Eder指出的,如果你在非静态上下文中这样做,你要小心。匿名子类集合将隐式地引用外部实例,并且如果它的寿命比集合长,这将是一个内存泄漏。

Note: As Lukas Eder points out, you want to be careful if you do this in a non-static context. The anonymous sub-class collection will implicitly have a reference to the outer instance and if it lives longer than the collection, this would be a memory leak. Have you ever thought of the possibility of a memory leak?

这篇关于双支架初始化 - 优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:56