Java遍历的多种写法

JDK1.4

Map   map   =   new   HashMap()   ;  
   
  Iterator   it   =   map.entrySet().iterator()   ;  
  while   (it.hasNext())  
  {  
  Map.Entry   entry   =   (Map.Entry)   it.next()   ;  
  Object   key   =   entry.getKey()   ;  
  Object   value   =   entry.getValue()   ;  
  }

JDK1.5

Map   m   =   new   HashMap();  
  for   (Object   o   :   map.keySet())   {  
          map.get(o);  
  }



    // For a set or list
for (Iterator it=collection.iterator(); it.hasNext(); ) {
Object element = it.next();
}

// For keys of a map
for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
}

// For values of a map
for (Iterator it=map.values().iterator(); it.hasNext(); ) {
Object value = it.next();
}

// For both the keys and values of a map
for (Iterator it=map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
}

 

你可能感兴趣的:(Java遍历的多种写法)