java基础 数据集合 hashmap hashtable

来源:互联网 发布:mac窗口切换 编辑:程序博客网 时间:2024/06/05 17:05

java 中 用法差不多   但是 hashtable 线程同步 

                                            hashtable 不能装空值

                                            hashmap  可以装空值 null



hashMap

public static void main(String[] args) {//创建一个 hashMap 对象HashMap hm = new HashMap();Emp emp1 = new Emp("s001","aaa",3.4f);Emp emp2 = new Emp("s002","bbb",3.4f);Emp emp3 = new Emp("s003","ccc",3.4f);hm.put("s001", emp1);hm.put("s002", emp2);//hm.put("s002", emp3);//键值一样的时候,会用emp3的信息覆盖hm.put("s003", emp3);//如果你要查找编号是s002if(hm.containsKey("s002")){System.out.println("have");   //Emp emp=(Emp)hm.get("s002");System.out.println("name="+ emp.getName());}else{System.out.println("no");}//遍历HashMap 中 所有的key 和 value   因为hashmap 的方法是get(value) 不能遍历Iterator  it = hm.keySet().iterator();while(it.hasNext()){String key=it.next().toString();//取出keyEmp emp=(Emp)hm.get(key);System.out.println("name"+ emp.getName());}}




0 0
原创粉丝点击