/**
* HashMap集合讲解
* HashMap集合不允许集合元素的Key重复
*/
package com.test;
import java.util.*;
public class test8 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap hm = new HashMap();
Employer emp1 = new Employer();
emp1.setName("xx");
emp1.setAge(22);
emp1.setSalary(2000.00f);
Employer emp2 = new Employer();
emp1.setName("zz");
emp1.setAge(22);
emp1.setSalary(4000.00f);
//添加对象到hashmap集合
hm.put("001", emp1);
hm.put("002", emp2);
if(hm.containsKey("001"))
{
Employer temp = (Employer) hm.get("001");
System.out.println("个人信息:"+"姓名:"+temp.getName()+" 年龄:"+temp.getAge()+" 工资:"+temp.getSalary());
}
else
{
System.out.println("没有该员工");
}
System.out.println("--------------使用迭代器遍历hashmap集合-----------------");
//使用迭代器遍历hashmap集合
Iterator it = hm.keySet().iterator();
while(it.hasNext()) //探测下一个元素是否存在,返回bool值
{
//取出key
String key = it.next().toString();
//通过key取出value
Employer temp_x = (Employer) hm.get(key);
System.out.println("个人信息:"+"姓名:"+temp_x.getName()+" 年龄:"+temp_x.getAge()+" 工资:"+temp_x.getSalary());
}
}
}
class Employer
{
private String name;
private int age;
private float salary;
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;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
小结: