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是一一对应的关系。
即HashMap中的Key,Value是一一对应的关系。
2、遍历HashMap 时使用 Iterator 。
3、HashMap在遍历时,并不是按照添加的前后顺序输出的!
输出顺序到底是什么规律呢?
4、Hashtable 与HashMap 在使用的”存取、遍历“等方法上几乎一致!! 其区别主要在于”线程同步“与否。