Map map = new HashMap();
map.put("1","hehehe");
map.put("2", "hahaha");
map.put("3", "xixixi");
map.put("4", "hihihi");
//第一种方法
Iterator iter = map.keySet().iterator();
while(iter.hasNext()) {
String key = (String)iter.next();
String value = (String)map.get(key);
System.out.println(key + "=" + value);
}
//第二种方法
Iterator it = map.keySet().iterator();
while(it.hasNext()) {
Entry entry = (Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + "=" + value);
}
//第一种方式使用增强for循环
for(Object obj : map.keySet()) {
String key = (String)obj;
String value = (String)map.get(key);
System.out.println(key + "=" + value);
}
//第二种方式使用增强for循环
for(Object obj : map.entrySet()) {
Entry entry = (Entry)obj;
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + "=" + value);
}
对 set 的遍历
1.迭代遍历:
Set<String> set = new HashSet<String>();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
}
2.for循环遍历:
for (String str : set) {
System.out.println(str);
}
优点还体现在泛型 假如 set中存放的是Object
Set<Object> set = new HashSet<Object>();
for循环遍历:
for (Object obj: set) {
if(obj instanceof Integer){
int aa= (Integer)obj;
}else if(obj instanceof String){
String aa = (String)obj
}
........
}