HashMap类,Hashtable类的用法

/**
 * 2018.8.3
 * 作者:小孟鱼
 * 功能:HashMap类,Hashtable类的用法
 */
package com.test;

import java.util.HashMap;
import java.util.Iterator;

public class Maplei {
            public static void main(String[] args) {
         
                //创建用一个HashMap对象
                HashMap hm=new HashMap();
                hm.put(null, null);
                System.out.println("测试"+hm.get(null));//HashMap可以将空值可以作为表的条目存放在key 和 value但是Hashtable不行
                
                Emp emp1=new Emp("s001","aa",1.4f);
                Emp emp2=new Emp("s002","bb",1.5f);
                Emp emp3=new Emp("s003","cc",1.6f);
                //将emp放到hm中
                hm.put("s001", emp1);
                hm.put("s002", emp2);
                hm.put("s002", emp3);//HashMap的解决方式是将emp3将s002的对象覆盖
                //查找编号
                //假设要找的编号为s001
                if(hm.containsKey("s002")) 
                {
                    System.out.println("有该员工");
                    //如何取出,键<-->值
                     Emp emp=(Emp)hm.get("s002");
                     System.out.println("名字"+emp.getName());
                }else 
                {
                    System.out.println("没有该员工");
                }
                //遍历HashMap中所有的key和vaval
                //Iterator迭代
                Iterator it=(Iterator) hm.keySet();
                
                
             //hasNext返回一个boolean
                while(it.hasNext())
                {
                    //取出key
                    it.next();
                }
            }
}
 

猜你喜欢

转载自blog.csdn.net/weixin_42133768/article/details/81447927