日期:2014-05-20  浏览次数:20720 次

HashMap中获取集合列表信息
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HashMapTest {

/**
* @param args
*/
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Goods goodes=new Goods();
Map<Integer ,Goods> map=new HashMap<Integer ,Goods>();
Goods good1=new Goods(1001,"吉百芝麻油",1.5,"125ml",300);
Goods good2=new Goods(1002,"雀巢奶香咖啡",2.4,"13g",20);
Goods good3=new Goods(1003,"脉动式蜜桃",7.0,"1.5l",500);
Goods good4=new Goods(1004,"桃李熟切片",6.5,"400g",10);
map.put(good1.getId(),good1);
map.put(good2.getId(),good2);
map.put(good3.getId(),good3);
map.put(good4.getId(),good4);

System.out.println(">> 新增商品");
System.out.print("请输入商品编号:");
int id=input.nextInt();
int index=getindex(map,id);//查找map集合当中的索引位置
if(index>=0){
Goods good=(Goods) map.get(index);
System.out.print("请输入商品名称:");
String name=input.next();
good.setGoodsName(name);
System.out.print("请输入商品单价:");
double Price=input.nextDouble();
good.setPrice(Price);
System.out.print("请输入商品单位:");
String Unit=input.next();
good.setUnit(Unit);
System.out.print("请输入商品库存:");
int Num=input.nextInt();
good.setNum(Num);
System.out.println("新增成功!");
map.put(good.getId(),good);
showIndex(map);//显示集合列表信息
}

}
   
private static void showIndex(Map<Integer, Goods> map) {
System.out.println("商品编号"+"\t"+"商品名称"+"\t"+"商品单价"+"\t"+"单位"+"\t"+"数量");
for(Goods goods:map){
  Iterator iterator=map.iterator();
  system.out.println(goods);
--------------------代码
}
}

private static int getindex(Map map, int id) {
int index=0;
for(int i=0;i<map.size();i++){
if(((Goods) map.get(i)).getId()==id){
index=i;
break;
}
}
return index;
}

}


------解决方案--------------------
HashMap<Integer,Goods> map = new HashMap<Integer,Goods>(); 
//put你自己的值
map.put(key,val);
map.put(key,val);
//获取所有map键的集合
Iterator<Integer> it = map.KeySet().iterator();
//根据每个键得到相应的值
while(it.hashNext()){
Goods goods=map.get(it.next());
}