🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ package arraylist.a4; import java.util.*; public class Test { public static void main(String[] args) throws Exception{ HashMap ee=new HashMap(); Sp sp1=new Sp("001","话梅",5f); Sp sp2=new Sp("002","薯片",8f); ee.put("001", sp1); ee.put("002", sp2);//键 值 if(ee.containsKey("002")){//不需要遍历 System.out.println("该食品的信息为:"); Sp sp=(Sp)ee.get("002"); System.out.println(sp.getMingcheng()); System.out.println(sp.getJiage()); }else{ System.out.println("对不起,没有该食品"); } } } class Sp{ private String bianhao; private String mingcheng; private float jiage; public Sp(String bianhao, String mingcheng, float jiage) { super(); this.bianhao = bianhao; this.mingcheng = mingcheng; this.jiage = jiage; } public String getBianhao() { return bianhao; } public void setBianhao(String bianhao) { this.bianhao = bianhao; } public String getMingcheng() { return mingcheng; } public void setMingcheng(String mingcheng) { this.mingcheng = mingcheng; } public float getJiage() { return jiage; } public void setJiage(float jiage) { this.jiage = jiage; } } ~~~ ![](https://box.kancloud.cn/79256ee93353937823c56a8739a5e8ae_163x122.png) HashMap的遍历 ~~~ package arraylist.a4; import java.util.*; public class Test { public static void main(String[] args) throws Exception{ HashMap ee=new HashMap(); Sp sp1=new Sp("001","话梅",5f); Sp sp2=new Sp("002","薯片",8f); ee.put("001", sp1); ee.put("002", sp2);//键 值 /*if(ee.containsKey("002")){//不需要遍历 System.out.println("该食品的信息为:"); Sp sp=(Sp)ee.get("002"); System.out.println(sp.getMingcheng()); System.out.println(sp.getJiage()); }else{ System.out.println("对不起,没有该食品"); }*/ //遍历 Iterator it =ee.keySet().iterator();//所有的键值都激活,都给取出来 while(it.hasNext()){//还有没有下一个,有为真,没有为假 String key=it.next().toString(); Sp sp=(Sp)ee.get(key); System.out.println("食品名称:"+sp.getMingcheng()); System.out.println("食品价格:"+sp.getJiage()+"元"); } } } class Sp{ private String bianhao; private String mingcheng; private float jiage; public Sp(String bianhao, String mingcheng, float jiage) { super(); this.bianhao = bianhao; this.mingcheng = mingcheng; this.jiage = jiage; } public String getBianhao() { return bianhao; } public void setBianhao(String bianhao) { this.bianhao = bianhao; } public String getMingcheng() { return mingcheng; } public void setMingcheng(String mingcheng) { this.mingcheng = mingcheng; } public float getJiage() { return jiage; } public void setJiage(float jiage) { this.jiage = jiage; } } ~~~ ![](https://box.kancloud.cn/e842ccc8d6743738e71620e3249155e4_185x137.png)