项目实战のCollection和Map

迈不过友情╰ 2022-09-23 10:48 267阅读 0赞

前面两篇文章讲了collection的list应用和set的应用

根据单列值和双列值分为collection和map然后根据是否有序将collection分为list和set。

Collection(单列值)

List(有序)

set(无序)

Map(键值对)

应用:collection适合进行显示和遍历,但是如果对数据进行操作的话用map的键值对很方便。以前只是做过相关的demo,现在项目中用到了,可以更淋漓尽致的理解理论知识,进行数据结构的选型:

购物车:包含很多个购物项的例子

  1. package cn.itcast.shop.cart.vo;
  2. import cn.itcast.shop.product.vo.Product;
  3. /*
  4. * 购物项
  5. * **/
  6. public class CartItem {
  7. public Product getProduct() {
  8. return product;
  9. }
  10. public int getCount() {
  11. return count;
  12. }
  13. public void setProduct(Product product) {
  14. this.product = product;
  15. }
  16. public void setCount(int count) {
  17. this.count = count;
  18. }
  19. public void setSubtotal(double subtotal) {
  20. this.subtotal = subtotal;
  21. }
  22. //小计自动计算
  23. public double getSubtotal() {
  24. return count*product.getShop_price();
  25. }
  26. private Product product;
  27. private int count;//某种商品数量
  28. private double subtotal;//小计
  29. }
  30. package cn.itcast.shop.cart.vo;
  31. import java.util.Collection;
  32. import java.util.LinkedHashMap;
  33. import java.util.Map;
  34. /*
  35. * 购物车
  36. * **/
  37. public class Cart {
  38. //购物项集合:Map的key是商品pid,value是购物项。hashMap是无序的
  39. private Map<Integer, CartItem> map= new LinkedHashMap<Integer, CartItem>();
  40. //购物总金额
  41. private double total;
  42. //购物车的功能
  43. public Collection<CartItem> getCartItems(){
  44. return map.values();//返回值是一个collection,取得是map的值的集合
  45. }
  46. //1将购物项添加到购物车
  47. public void addCart(CartItem cartItem){
  48. /*判断购物车是否存在购物项
  49. * *若存在:
  50. * *数量增加
  51. * *总计+=购物项
  52. * *若不存在
  53. * *向map中增加购物项
  54. * *总计+=购物项
  55. *
  56. *
  57. * */
  58. //获得商品id
  59. Integer pid= cartItem.getProduct().getPid();
  60. //判断购物车中是否存在购物项
  61. if(map.containsKey(pid)){
  62. //存在
  63. CartItem _cartItem=map.get(pid);//原来的购物项
  64. _cartItem.setCount(_cartItem.getCount()+cartItem.getCount());
  65. }else{
  66. //不存在
  67. map.put(pid, cartItem);
  68. }
  69. total+=cartItem.getSubtotal();
  70. }
  71. public double getTotal() {
  72. return total;
  73. }
  74. //2从购物车移除购物项
  75. public void removeCart(Integer pid){
  76. //将购物项移除购物车map.remove()的时候返回的是移除的购物项
  77. CartItem cartItem= map.remove(pid);
  78. //总结-=移除的购物项的小计
  79. total-=cartItem.getSubtotal();
  80. }
  81. //3清空购物车
  82. public void clearCart(){
  83. //将所有的购物项清空
  84. map.clear();
  85. //将总计设置成0
  86. total=0;
  87. }
  88. }

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读

    相关 collectionMap区别

    线性表,链表,哈希表是常用的数据结构,在进行Java开发时,JDK已经为我们提供了一系列相应的类来实现基本的数据结构。这些类均在java.util包中。本文试图通过简单的描述,

    相关 collectionmap

    ![这是我自己整理的collection和map的一些资料以后会继续完善][collection_map] 这部分的文本摘自其他网络博客 Collection接口,包含l

    相关 collectionmap

    ![这是我自己整理的collection和map的一些资料以后会继续完善][collection_map] 这部分的文本摘自其他网络博客 Collection接口,包含l