1、數組周遊:for循環(這裡隻列出增強版,不适合指派)
//數組
String[] array={"a","b","c"};
public void testArray(){
for(String s:array){
System.out.print(s); }
System.out.println("");
}
2、List周遊:使用iterator疊代器進行周遊
//list
public void testList(){
List l=new ArrayList();
l.add("1");
l.add("2");
l.add("3");
Iterator it=l.iterator();
while(it.hasNext()){
String i=(String)it.next();
System.out.print(i);
}
System.out.println("");
}
3、Map周遊:同樣使用疊代器,不過要先使用keyset()方法取出key值
//map
public void testMap(){
Map map=new LinkedHashMap();
map.put("1","a");
map.put("2", "b");
map.put("3", "c");
Set keys=map.keySet();
Iterator it=keys.iterator();
while(it.hasNext()){
String its=(String) map.get(it.next().toString());
System.out.print(its);
}
}
4、亦可以使用增強型for循環進行map周遊
public void testMap1(){
Map map=new LinkedHashMap();
map.put("1","a");
map.put("2", "b");
map.put("3", "c");
Set keys=map.keySet();
Iterator it=keys.iterator();
for(Object obj:keys){
String key=(String)obj;
String value=(String) map.get(key);
System.out.print(value);
}
}