java集合框架代码 java集合框架是什么,有什么优点( 二 )


结果:
{3=VC++, 5=c, 2=VB, 4=c++, 6=basic, 1=java}
第七次:
aa.put("1","java");
aa.put("2","VB");
aa.put("3","VC++");
aa.put("4","c++");
aa.put( "5","c");
aa.put( "6","basic");
aa.put( "7","Jscript");
结果:
{3=VC++, 5=c, 7=Jscript, 2=VB, 4=c++, 6=basic, 1=java}
由以上结果我们可以看出来,在HashMap里,添加顺序并不是按从前向后的顺序添加的,也不是按从后向前添加的,在HashMap的文挡帮助里有这么一句话:"此类不保证映射的顺序,特别是它不保证该顺序恒久不变 。",如果你又想用Map又想保持顺序 , 可以使用LinkedHashMap,它和HashMap一样,但是可以保证插入顺序,但是这样也增加了一点点开销.
Java集合框架2根据你上面的提示和程序里的要求,修改了Database,新增了衣服的方法 。每次计算的价格可以写成共通方法 。希望其他人有好的建议也发上来 。
import java.util.HashMap;
import java.util.Map;
public class Database {
private MapInteger, McBean data = https://www.04ip.com/post/new HashMapInteger, McBean();
public Database(){
McBean bean = new McBean();
bean.setNid(1);
bean.setSname("地瓜");
bean.setNprice(2.0);
bean.setSdescription("新鲜的地瓜");
data.put(1, bean);
bean = new McBean();
bean.setNid(2);
bean.setSname("土豆");
bean.setNprice(1.2);
bean.setSdescription("又好又大的土豆");
data.put(2, bean);
bean = new McBean();
bean.setNid(3);
bean.setSname("丝瓜");
bean.setNprice(1.5);
bean.setSdescription("本地丝瓜");
data.put(3, bean);
bean = new McBean();
bean.setNid(4);
bean.setSname("衣服");
bean.setNprice(30);
bean.setSdescription("衣服");
data.put(4, bean);
}
public McBean getMcBean(int nid){
return data.get(nid);
}
}
public class McBean {
private Integer nid; //商品编号
private String sname; //名称
private double nprice; //价格
private String sdescription; //描述
public Integer getNid() {
return nid;
}
public void setNid(Integer nid) {
this.nid = nid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public double getNprice() {
return nprice;
}
public void setNprice(double nprice) {
this.nprice = nprice;
}
public String getSdescription() {
return sdescription;
}
public void setSdescription(String sdescription) {
this.sdescription = sdescription;
}
}
public class OrderItemBean {
private McBean mcbean; //商品
private int count; //商品数量
public McBean getMcbean() {
return mcbean;
}
public void setMcbean(McBean mcbean) {
this.mcbean = mcbean;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ShoppingCar {
private double totalPrice; //购物车所有商品总价格
private int totalCount; //购物车所有商品数量
private MapInteger,OrderItemBean itemMap; //商品编号与订单项的键值对
public ShoppingCar(){
//初始化购物车
itemMap = new HashMapInteger, OrderItemBean();
Database db = new Database();
McBean bean = new McBean();
OrderItemBean orderItem1 = new OrderItemBean();
OrderItemBean orderItem2 = new OrderItemBean();
OrderItemBean orderItem3 = new OrderItemBean();
bean = db.getMcBean(1);
orderItem1.setMcbean(bean);
orderItem1.setCount(2);

推荐阅读