一.遍历HashMap
Map<Integer, String> map = new HashMap<Integer, String>();
for(int i=0;i<100;i++)
{
map.put(i, "123");
}
方法一:效率比方法二高
for(Entry<Integer, String> entry:map.entrySet())
{
System.out.println(entry.getKey()+"="+entry.getValue());
}
for (Iterator<Entry<Integer,String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
Entry<Integer, String> entry = iterator.next();
}
方法二:
for(Object obj : map.keySet()) {
Object key = obj;
Object value = map.get(obj);
System.out.println(value);
}
二.遍历HashSet
Set set = new HashSet();
for(int i=0;i<100;i++)
{
set .add("123");
}
for(Iterator it=set.iterator();it.hasNext();)
{
System.out.println(it.next());
}
三.遍历Hashtable(同步、线程安全的)
Hashtable table = new Hashtable();
table.put(1, "1");
table.put(2, "1");
table.put(3, "1");
//遍历key
Enumeration e = table.keys();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}
//遍历value
e = table.elements();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}