1. 雙括弧語法
// 用于集合初始化
List<String> list = new ArrayList<String>(){{
add("dog");
add("cat");
add("monkey");
}};
Set<String> set = new HashSet<String>(){{
add("cat");
add("cat");
}};
Map<String, String> map = new HashMap<String, String>(){{
put("name", "jim");
put("age", "17");
}};
2. foreach:增強for循環(huán)
本質(zhì)上是使用了Iterator迭代器和do-while循環(huán)。
在foreach迭代中,如果對迭代集合做了增加元素、刪除元素等操作的話,會拋出ConcurrentModificationException異常。
for(String item: list){
if(item.equals("dog")){
list.remove(item);
}
}
未完待續(xù)