java之HashMap的遍历Iterator

package com.ql_2;
/*
* 功能:HashMap 的使用
*/
import java.util.*;

public class Test_2 {

public static void main(String[] args) {
// TODO 自动生成的方法存根
HashMap hm=new HashMap();
Emp emp1=new Emp("s001","aaa",3.4f);
Emp emp2=new Emp("s002","花荣",3.5f);
Emp emp3=new Emp("s003","李奎",3.6f);
hm.put("s001", emp1);
hm.put("s002", emp2);
hm.put("s002", emp3);
//查找编号s001
if(hm.containsKey("s001"))//containsKey()返回boolean
{
System.out.println("找到该员工");
Emp emp=(Emp)hm.get("s001");
System.out.println("名字:"+emp.getName());
}
if(hm.containsKey("s002"))
{
System.out.println("找到该员工");
Emp emp=(Emp)hm.get("s002");
System.out.println("名字:"+emp.getName());
}
//遍历HashMap 中所有的Key和Values
//Iterator迭代
Iterator it=hm.keySet().iterator();
while(it.hasNext())
{
//取出key
String key=it.next().toString();
//通过key取出values
Emp emp=(Emp)hm.get(key);
System.out.println("姓名:"+emp.getName());
System.out.println("工资:"+emp.getSal());

}
}

}

//雇员类
class Emp
{
private String empno;
private String name;
private float sal;
//构造函数
Emp(String empno,String name,float sal)
{
this.empno=empno;
this.name=name;
this.sal=sal;
}
public String getEmpno()
{
return empno;
}
public void setEmpno(String empno)
{
this.empno = empno;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public float getSal()
{
return sal;
}
public void setSal(float sal)
{
this.sal = sal;
}
}

posted @ 2014-05-23 21:26  加肥猫咪  阅读(...)  评论(...编辑  收藏