1 HashMap<String, String> map = new HashMap<String,String>(){ 2 private static final long serialVersionUID = 1L; 3 {put("key1","value1");} 4 {put("key2","value2");} 5 };
list也有类似写法:
1 invite(new ArrayList<String>(){ 2 { 3 add("Harry"); 4 add("Tony"); 5 } 6 }; 7 )
其实这是使用了内部类的语法 -- 双括号初始化
外层括号创建了 ArrayList 的一个匿名子类, 内部括号则是一个初始化块。