JAVA-HashMap 问题为什么遍历出现了问题?

import java.util.*;
public class HashM {

public static void main(String[] args) {
    HashMap hh = new HashMap();
    Emp emp1 = new Emp("1", "李白", 1.1f);
    Emp emp2 = new Emp("2", "李红", 2.1f);
    Emp emp3 = new Emp("3", "李银", 3.1f);
    hh.put(1, emp1);
    hh.put(2, emp2);
    hh.put(3, emp3);
    if(hh.containsKey(3)) {
        System.out.println("存在这个人");
        Emp tem = (Emp)hh.get(3);
        System.out.println("名字是" + tem.getName());
    } else {System.out.println("不存在这个人");}
    //遍历哈希数组 使用迭代(遍历的是Key)
    Iterator it = hh.keySet().iterator();
    //判断是否还有下一个值
    while(it.hasNext()) {
        //取出键值Key ,因为之前我们定义的键值是String类型
        String key = it.next().toString();
        //取出value值
        Emp emp = (Emp)hh.get(key);
        System.out.println("名字是" + emp.getName());
        System.out.println("薪水是" + emp.getSal());
    }
}

}
class Emp {
private String empNo;
private String name;
private float 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;
}

public Emp(String empNo, String name, float sal) {
    this.empNo = empNo;
    this.name = name;
    this.sal = sal;
}

}

猜你喜欢

转载自blog.csdn.net/zaza_a/article/details/81750801