[Java] HashMap的简单使用 →→→→→进入此内容的聊天室

来自 , 2019-12-04, 写在 Java, 查看 171 次.
URL http://www.code666.cn/view/eaa32c96
  1. /**
  2.  * 功能:HashMap的简单使用
  3.  */
  4.  
  5.  
  6. package com.text;
  7.  
  8. import java.util.HashMap;
  9. import java.util.Iterator;
  10.  
  11. public class Text2 {
  12.  
  13.         public static void main(String[] args) {
  14.                 //创建一个HashMap
  15.                 HashMap eh=new HashMap();
  16.                
  17.                 Emp emp1=new Emp("001", "宋江", 1000f);
  18.                 Emp emp2=new Emp("002", "李逵", 1200f);
  19.                 Emp emp3=new Emp("003", "吴用", 1500f);
  20.                
  21.                 //将员工emp放入eh
  22.                 eh.put("001", emp1);
  23.                 eh.put("002", emp2);
  24.                 eh.put("003", emp3);
  25.                
  26.                 //按key值查找,即按员工编号查找
  27.                 if (eh.containsKey("001")) {
  28.                         System.out.println("有该员工!");
  29.                        
  30.                         Emp emp=(Emp)eh.get("001");
  31.                         System.out.println("名字:"+emp.getName());
  32.                 }else {
  33.                         System.out.println("没有该员工!");
  34.                 }
  35.                
  36.                 //遍历HashMap中的key和value。
  37.                 //用Iterator迭代器
  38.                 Iterator it=eh.keySet().iterator();
  39.                
  40.                 while(it.hasNext()){
  41.                         //取出key
  42.                         String key=it.next().toString();
  43.                         //通过key取出value
  44.                         Emp emp=(Emp)eh.get(key);
  45.                         System.out.println("编号"+"    名字:"+"  工资");
  46.                         System.out.println(emp.getEmNum()+"  "+emp.getName()+"    "+emp.getSal());
  47.                 }
  48.  
  49.  
  50.         }
  51.  
  52. }

回复 "HashMap的简单使用"

这儿你可以回复上面这条便签

captcha