Double brace initialization with nested collections

♀尐吖头ヾ 提交于 2019-12-23 07:58:34

问题


I know I can declare and initialize a List using double braces:

// (1)
List<Object> myList = new ArrayList<object>(){{
    add("Object1");
    add("Object2");
}};

But I want a List of <Map<Object,Object>>:

// (2)
List<Map<Object,Object>> myList = new ArrayList<Map<Object,Object>>();

How can I use double brace initialization (see (1)) with nested collections? My goal is to declare and initialize the data structure in a single line.

Also I would like to know if there are certain drawbacks when using double brace initialization I have to be aware of.


回答1:


Avoid double brace initialization as it a) surprises your colleagues and is hard to read, b) harms performance and c) may cause problems with object equality (each object created has a unique class object).

If you're working on a code style guide this kind of trickery belongs in the don't section.

If you really want to be able to create lists and maps inline, just go ahead and create a few factory methods. Could look like this:

List l = Lists.of(
    Maps.of(new Entry("foo", "bar"), new Entry("bar", "baz")),
    Maps.of(new Entry("baz", "foobar"))
);

However, Vangs example shows exactly how the syntax for your example is for double brace initialization.




回答2:


It's not good idea, because it's hard to read, but you can do following:

List<Map<Object,Object>> myList = new ArrayList<Map<Object,Object>>() {{
                    add(new HashMap<Object, Object>() {{
                        put(key, obj);
                    }});
                }};


来源:https://stackoverflow.com/questions/28410359/double-brace-initialization-with-nested-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!