HashMap的键值和遍历
1,HashMap输出具有唯一性,当两个键值一致时输出,最后一个会覆盖掉前一个,关键词containsKey
2,循环输出时,不是用之前的for方法,而是使用Iterator 和While(**.hasNext)方法
集合类中的比较:
1,list没有键值,Map有键值,键值作为唯一的标识是单独添加的跟对象的属性无关,如学号
2,ArrayList和hashMaP是线程异步的,效率高安全性低,Vector和HashTable是线程同步的,效率低而安全性高
3,同步和异步举例:如游戏中双方,A打中B,两边同时显示打中则为同步,A显示B被打中,B没有显示,表示异步,单机游戏中是异步,对战游戏中同步
import java.util.*;
public class L45
{
public static void main(String[] args)
{
HashMap ee=new HashMap();
Sp sp1=new Sp("001","香肠",20);
Sp sp2=new Sp("002","果浦",10);
Sp sp3=new Sp("003","面包",2);
ee.put("001",sp1);
ee.put("002",sp2); // 键 值
ee.put("003",sp3);
/* if(ee.containsKey("002")) // 不需要遍历
{
System.out.println("该食品信息为");
Sp sp=(Sp)ee.get("002");
System.out.println(sp.gettMingcheng());
System.out.println(sp.gettJiage());
}
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.gettMingcheng());
System.out.println("食品价格:"+sp.gettJiage()+"元");
}
}
}
class Sp//主要有三步,第一步是定义变量, 第二个定义构造函数,第三个set和get
{
private String bianhao;
private String mingcheng;
private float jiage;
Sp(String bianhao,String mingcheng,float jiage)
{
this.mingcheng=mingcheng;
this.bianhao=bianhao;;
this.jiage=jiage;;
}
public String gettBianhao() {
return bianhao;
}
public void setBianhao(String bianhao) {
this.bianhao = bianhao;
}
public String gettMingcheng() {
return mingcheng;
}
public void setMingcheng(String mingcheng) {
this.mingcheng = mingcheng;
}
public void setJiage(float jiage) {
this.jiage = jiage;
}
public float gettJiage() {
return jiage;
}
}