import java.util.*; public class IterateMap { public static void main(String[] args) { Map hm=new HashMap(); hm.put(10001,"Tom"); hm.put(10003,"Jerry"); hm.put(10002,"John"); hm.put(10004,"Lili"); Set keySet=hm.keySet(); //获取Map的键集合 Iterator ii=keySet.iterator(); //获取键集合的迭代器 while(ii.hasNext()) { Object okey=ii.next(); Integer i=(Integer) okey; // 强制类型转换 String s= (String) hm.get(okey); //通过键获取相应的值 System.out.println("键:"+i.intValue() +",值:"+s+",值长度:"+s.length()+"。"); } /* Collection cvalue=hm.values(); //获取Map中所有值的Collection for(Object otemp:cvalue) { //用for-each循环对所有值进行遍历 String s=(String)otemp; //对引用进行强制类型转换 System.out.println("值:"+s+",值长度:"+s.length()+"。"); } */ Collection cvalue = hm.values();//获取Map中所有值的Collection Iterator it = cvalue.iterator();//获取值集合的迭代器 while(it.hasNext()){ String s = (String)it.next(); System.out.println("值:"+s+",值长度:"+s.length()+"。"); } } }
/** /* Set,List,Collection这三个接口中都有 iterator()方法。所以,在很多地方,都将它的子类或子结接赋给该三个接口。即父类(接口)子对象模式。//创建实现Collection接口的类的对象 Collection cset = new HashSet(); Collection clist = new ArrayList(); List list = new ArrayList(); //获取迭代器 Iterator it1 = cset.iterator(); Iterator it2 = clist.iterator(); Iterator it3 = list.iterator; 这样就可以迭代出来一个一个的对象了。 */
ArrayList和HashMap是异步的,Vector和HashTable是同步的, 所以Vector和HashTable是线程安全的, 而ArrayList和HashMap并不是线程安全的。
因为同步需要花费机器时间,所以Vector和HashTable的执行效率要低于 ArrayList和HashMap。 Collection接口实现类层次├List 接口 ├LinkedList 链表 ├ArrayList 顺序结构动态数组类 └Vector 向量 └Stack 栈 └Set Map 接口实现类层次Map ├Hashtable ├HashMap └WeakHashMap List接口
|
|