-1

I do not understand why my map value is not being incremented!!!

<% Collection<Product> items = basket.getItems();
HashMap<Product,Integer> itemMap = new HashMap<Product,Integer>();

for(Product p : items){
    if(!itemMap.containsKey(p)){
        itemMap.put(p,1);}
    else{itemMap.put(p, itemMap.get(p) + 1);}
    out.println("<p>"+itemMap+"</p>");
}%>

Every-time the value is 1!

recurf
  • 237
  • 4
  • 16
  • 1
    The most likely reason is the `Product` doesn't override `hashCode` and `equals` – Eran Mar 05 '16 at 18:08
  • Could you please share `Product`'s implementation? – Mureinik Mar 05 '16 at 18:08
  • 2
    The probable explanation is that you don't have any duplicate product in the collection. Is there a product that `equals` another one in the collection? Also, please refrain from using scriptlets. Put that code in a servlet. – JB Nizet Mar 05 '16 at 18:10

1 Answers1

-1

Ok I fixed it! Dont ask me why but it works?!

<% Collection<Product> items = basket.getItems();
HashMap<String,Integer> itemMap = new HashMap<String,Integer>();
ArrayList<String> dumbArray = new ArrayList<String>();

for(Product p : items){
    dumbArray.add(p.toString());
}

for(String p : dumbArray){
    if(!itemMap.containsKey(p)){
        itemMap.put(p,1);}
    else{itemMap.put(p, itemMap.get(p) + 1);}
    out.println("<p>"+itemMap+"</p>");
}%>

Arrays ftw?

recurf
  • 237
  • 4
  • 16
  • This just seems to reinforce what Eran and JB Nizet said, none of the values are equal, but their string representations are. Here is a [SnackOverflow question](http://stackoverflow.com/questions/410236/how-to-ensure-hashcode-is-consistent-with-equals) that might help clarify how to resolve this. – Obicere Mar 05 '16 at 18:26
  • @Obicere yes, i took his input to aid my fix? why the vote down, its a bit unfair – recurf Mar 05 '16 at 18:29
  • 1
    This solution is a bit like sealing a hole in a dam with chewing gum. Instead of solving the underlying problem, you've simply avoided having to deal with it. But, overriding `hashCode` and `equals` is a far better approach to solving this problem and sticking to Java's principles. – Obicere Mar 05 '16 at 18:32
  • @Obicere Okay point noted, right now i was just looking for a fix, but in future i will keep this in mind thank you – recurf Mar 05 '16 at 18:34