Java集合——HashMap和Hashtable应用实例
2017-02-26 19:39
288 查看
package com.shuzu; import java.util.HashMap; import java.util.Iterator; public class HashMapTest { public static void main(String[] args) { // TODO Auto-generated method stub Student s1 = new Student("小明",25); Student s2 = new Student("小刚",24); Student s3 = new Student("小胖",23); HashMap hm = new HashMap(); hm.put("小明", s1); hm.put("小刚", s2); hm.put("小强", s3); //1.取出信息 if(hm.containsKey("小明")){ System.out.println("有该学生!"); Student st = (Student) hm.get("小明"); System.out.println("姓名:"+st.getName()+" 年龄:"+st.getAge()); }else { System.out.println("没有该学生!"); } //2.利用 Iterator ,遍历 HashMap Iterator it = hm.keySet().iterator(); while(it.hasNext()){ String key = it.next().toString(); //上一步得到 “Key”,现在取出对象 Student st = (Student) hm.get(key); System.out.println("找到学生:"+st.getName()+" 年龄:"+st.getAge()); } } } class Student{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } private int age; public Student(String name, int age) { super(); this.name = name; this.age = age; } }
注意:
1、HashMap 如果在同一个“Key“上添加不同的”object“,HM会默认后者 覆盖前者。
hm.put("小明", s1);
hm.put("小刚", s2);
hm.put("小明", s3);
如上Code,第三行s3将覆盖s1 。
即HashMap中的Key,Value是一一对应的关系。
2、遍历HashMap 时使用 Iterator 。
3、HashMap在遍历时,并不是按照添加的前后顺序输出的!
输出顺序到底是什么规律呢?
4、Hashtable 与HashMap 在使用的”存取、遍历“等方法上几乎一致!! 其区别主要在于”线程同步“与否。
相关文章推荐
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- java集合:HashMap和Hashtable的区别
- JavaHashMapHashTable集合类(转)
- [疯狂Java]集合:HashMap、Hashtable(摒弃)、LinkedHashMap、Properties
- JAVA中的数据结构——集合类(线性表:Vector、Stack、LinkedList、set接口;键值对:Hashtable、Map接口<HashMap类、TreeMap类>)
- 19.java HashMap 的应用实例
- Java 集合:Map 系列(HashMap,HashTable)
- Java基础知识强化之集合框架笔记66:Map集合面试题之HashMap和Hashtable区别(重要)
- java集合(ArrayList、vector、HashMap、HashTable)源码剖析
- Java集合学习--HashMap、LinkedHashMap、TreeMap、HashTable
- Java集合之Hashtable<K,V>,TreeMap<K,V>,HashMap<K,V>自动排序
- [JAVA修炼之路四]-集合(ConCurrentHashMap HashTable)
- 黑马程序员 java 基础 毕向东 面向对象 集合框架 Map HashTable HashMap TreeMap
- Java 集合系列 11 hashmap 和 hashtable 的区别
- 【Map集合总结】HashMap---Hashtable---TreeMap三者的区别和相关的应用!!
- Java 集合系列14之 Map总结(HashMap, Hashtable, TreeMap, WeakHashMap等使用场景)