2015-08-28 76 views
2

我正在使用在線商店項目。目前,我正試圖增加產品添加到購物車的可能性,無論用戶是否登錄。我使用會話bean方法來做到這一點。在HashMap中使用相同的密鑰存儲/取消設置多個值

@Inject ShoppingCartSessionBean shoppingCartSessionBean; 

@POST 
public boolean addToCart(@PathParam("productid") int newProductId, @PathParam("qu") int newProductQuantity) { 
    shoppingCartSessionBean.setCartItems(newProductId); 
    shoppingCartSessionBean.setProductQuantity(newProductQuantity); 
    return true;  
} 

我想將id的存儲在散列映射中。但是,目前我只能爲我的setter方法設置一個id。

@Stateful 
@SessionScoped 
public class ShoppingCartSessionBean implements Serializable{ 

HashMap<Integer, Integer> newmap = new HashMap<Integer, Integer>(); 

public int addToHashMap() { 

return array of productId's. 
} 

private static final long serialVersionUID = -5024959800049014671L; 

private int productId; 

private int productQuantity; 

//getters and setters 

Map<Integer, ShoppingCartSessionBean> hm = new HashMap<Integer, ShoppingCartSessionBean>(); 

後來我使用實體管理器來檢查設置了哪個ID的ID,並將所有有關該ID的信息發回給用戶。由於空間問題,我沒有在會話bean中存儲所有值。

Query q = em.createQuery("SELECT c FROM Items c WHERE c.productId = :itemid"); 
     q.setParameter("itemid", shoppingCartSessionBean.addToHashMap()); 

所以,我有幾個問題:

  1. 它是不錯的選擇存儲在哈希表這樣的信息?或者我應該使用cookie來代替?

  2. 我的addToHashmap方法應該如何在散列圖中存儲多個id? (我嘗試了一個簡單的int [] array = {123,456}來使用我的實體管理器打印出來,但是我得到了JSON錯誤...)。

  3. 從散列圖中刪除/取消設置這些信息的最佳方法是什麼?

我希望我的信息很清楚,如果您錯過了某些東西 - 現在就讓我。

+0

還有這個問題... – Laurynas

回答

0

點2和3.您需要檢查是否存在散列衝突,在正面情況下您需要對其進行處理。看下面的代碼。

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 


public class HashMapTest { 

    private static HashMap<String, List<String>> map = new HashMap<String, List<String>>(); 

    public static void insert(String key, String value){ 
     List<String> list = map.get(key); 
     if (list == null){ 
      list = new ArrayList<String>(); 
      map.put(key, list); 
     } 
     list.add(value); 
    } 



    public static void main(String[] args){ 

     insert("10", "V1"); 
     insert("10", "V2"); 
     insert("20", "V3"); 
     insert("20", "V4"); 
     insert("30", "V5"); 
     List<String> values10 = map.get("10"); 
     System.out.println(values10); 
     List<String> values20 = map.get("20"); 
     System.out.println(values20); 
     List<String> values30 = map.get("30"); 
     System.out.println(values30); 
    } 
} 
相關問題