HashMap的使用
import java.util.HashMap; import java.util.Iterator; //HashMap<key, value>():键值对的形式存储数据,相当于编号存储 //Key值重复会覆盖;无序存储 //一般用迭代器循环输出的都是无序存储的 public class HashMap类 { public static void main(String[] args) { //利用Map接口实现 //Map hm=new HashMap(); HashMap hm=new HashMap(); Emp emp1=new Emp("001", "张三", 1200); Emp emp2=new Emp("002", "李四", 2200); Emp emp3=new Emp("003", "王五", 2200); //存储数据 hm.put("001", emp1); hm.put("002", emp2); hm.put("002", emp3); //查找数据 if(hm.containsKey("002")){ System.out.println("存在"); //取值 Emp emp=(Emp)hm.get("002"); System.out.println("姓名:"+emp.getName()); }else{ System.out.println("不存在"); } //遍历HashMap中所有Key和Value(迭代器) Iterator it=hm.keySet().iterator(); //hasNext()返回一个boolean while(it.hasNext()){ //取key String key=it.next().toString(); //通过key取value Emp emp=(Emp)hm.get(key); System.out.println("学号:"+emp.getEmpNo() +",姓名:"+emp.getName()+",薪水:"+emp.getSal()); } } }
class Emp{ private String empNo; private String name; private float sal; public Emp(String empNo, String name, float sal) { super(); 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; } }