[java]代码库
package cn.Tim.org;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class ForeachDemo1 {
@Test
public void ArrayTest() {
int arr[] = {1,2,3};
for(int i: arr) {
System.out.println(i);
}
}
@Test
public void SetTest() {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
for(Object obj : list) {
int i = (Integer) obj;
System.out.println(i);
}
}
@Test
public void MapOldTest() {
Map map = new HashMap();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
//通过keySet迭代Map
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext()) {
Integer key = (Integer)it.next();
String value = (String)map.get(key);
System.out.println(key + ":" + value);
}
//通过entrySet迭代Map
Set set1 = map.entrySet();
Iterator it1 = set1.iterator();
while(it1.hasNext()) {
Map.Entry entry = (Map.Entry) it1.next();
Integer key = (Integer)entry.getKey();
String value = (String)entry.getValue();
System.out.println(key + ":" + value);
}
}
@Test
public void MapNewTest() {
Map map = new HashMap();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
//通过keySet,for-each来迭代Map
for(Object obj : map.keySet()) {
Integer key = (Integer)obj;
String value = (String)map.get(key);
System.out.println(key + ":" + value);
}
//通过entrySet,for-each来迭代Map
for(Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
Integer key = (Integer)entry.getKey();
String value = (String)entry.getValue();
System.out.println(key + ":" + value);
}
}
}
[源代码打包下载]
中级程序员
by: 乐果404 发表于:2013-07-20 19:37:35 顶(0) | 踩(0) 回复
for--each只适合数据的遍历,不适合于修改数据。
回复评论