另一种填充数组列表的方法



为什么可以呢?你能告诉我怎么做和为什么吗?

List<String> list = new ArrayList<String>() {
    {
        add("one");
        add("two");
        add("three");
    }
};
for ( String element : list )
    System.out.println(element);

这意味着您创建了一个扩展arraylist的类,并添加了一个静态块。

List<String> list = new ArrayList<String>(){};  // At this step you have created an instance of an anonymus class assigned to the list varibale
new ArrayList<String>() {
        {
        add("one");
        add("two");
        add("three");
        } // This is a static block inside your newly created anonymus class. 
};

最新更新