package cn.itcast.jdk15;java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;數組
/*
jdk1.5出現的新特性---->加強for循環jvm
加強for循環的做用: 簡化迭代器的書寫格式。(注意:加強for循環的底層仍是使用了迭代器遍歷。)對象
加強for循環的適用範圍: 若是是實現了Iterable接口的對象或者是數組對象均可以使用加強for循環。接口
加強for循環的格式:
for(數據類型 變量名 :遍歷的目標){
}rem
加強for循環要注意的事項:
1. 加強for循環底層也是使用了迭代器獲取的,只不過獲取迭代器由jvm完成,不須要咱們獲取迭代器而已,因此在使用加強for循環變量元素的過程當中不許使用集合
對象對集合的元素個數進行修改。
2. 迭代器遍歷元素與加強for循環變量元素的區別:使用迭代器遍歷集合的元素時能夠刪除集合的元素,而加強for循環變量集合的元素時,不能調用迭代器的remove方法刪除元素。
3. 普通for循環與加強for循環的區別:普通for循環能夠沒有變量的目標,而加強for循環必定要有變量的目標。get
*/
public class Demo2 {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
//添加元素
set.add("狗娃");
set.add("狗剩");
set.add("鐵蛋");
/*
//使用迭代器遍歷Set的集合.
Iterator<String> it = set.iterator();
while(it.hasNext()){
String temp = it.next();
System.out.println("元素:"+ temp);
it.remove();
}
//使用加強for循環解決
for(String item : set){
System.out.println("元素:"+ item);
}
int[] arr = {12,5,6,1};
普通for循環的遍歷方式
for(int i = 0 ; i<arr.length ; i++){
System.out.println("元素:"+ arr[i]);
}
//使用加強for循環實現
for(int item :arr){
System.out.println("元素:"+ item);
}
//需求: 在控制檯打印5句hello world.
for(int i = 0 ; i < 5; i++){
System.out.println("hello world");
}
*/
//注意: Map集合沒有實現Iterable接口,因此map集合不能直接使用加強for循環,若是須要使用加強for循環須要藉助於Collection
// 的集合。
HashMap<String, String> map = new HashMap<String, String>();
map.put("001","張三");
map.put("002","李四");
map.put("003","王五");
map.put("004","趙六");
Set<Map.Entry<String, String>> entrys = map.entrySet();
for(Map.Entry<String, String> entry :entrys){
System.out.println("鍵:"+ entry.getKey()+" 值:"+ entry.getValue());
}
}it
}io