当前位置: 代码迷 >> Java Web开发 >> HashMap剔除对象
  详细解决方案

HashMap剔除对象

热度:316   发布时间:2016-04-17 12:36:12.0
HashMap删除对象
我想问一下如何用hashmap删除一个自定义对象,在这个public void removeProduct(cartBean removeId)方法中我该怎么写才能删除一个对象?
public class cartBean {
  private String username;
  private String itemId;
  public cartBean() {
  }
  public cartBean(String id,String name) {
  this.itemId=id;
  this.username=name;
  }
  public void setUsername(String username) {
  this.username = username;
  }

  public void setItemId(String itemId) {
  this.itemId = itemId;
  }

  public String getUsername() {
  return username;
  }

  public String getItemId() {
  return itemId;
  }

}
import java.util.*;

public class cart {
  private HashMap hp = new HashMap();
  public cart() {
  }

  public void addItem(String itemId, String uname, Integer quantity) {
  boolean bb = false;
  cartBean cb = new cartBean(itemId, uname);
  Set set = hp.entrySet();
  java.util.Iterator it = set.iterator();
  while (it.hasNext()) {
  Map.Entry e = (Map.Entry) it.next();
  cartBean xx=(cartBean)e.getKey();
  if (xx.getUsername().equals(cb.getUsername()) && xx.getItemId().equals(cb.getItemId())) {
  bb = true;
  Integer count = (Integer) e.getValue() + new Integer(1);
  e.setValue(count);
  }
  }
  if (!bb) {
  hp.put(cb, quantity);
  }
  }

  public void removeProduct(cartBean removeId) {
  }

  public HashMap getHp() {
  return hp;
  }

  public void setHp(HashMap hp) {
  this.hp = hp;
  }
}
我想问一下如何用hashmap删除一个自定义对象,在这个public void removeProduct(cartBean removeId)方法中我该怎么写才能删除一个对象?

------解决方案--------------------
1. 楼主命名不规范
2. 建议使用generic
3. 代码 hp.remove(removeId);

------解决方案--------------------
HashMap有remove(Object key) 方法

代码有点乱。。。。
而且一点注释也没有的。。。
看起都头痛。。。

------解决方案--------------------
public Object remove(Object key)
Removes the mapping for this key from this map if present. 

Specified by:
remove in interface Map
Overrides:
remove in class AbstractMap
Parameters:
key - key whose mapping is to be removed from the map. 
Returns:
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key.
  相关解决方案