LinkedHashMap中是否包含一个Key的判断

在LinkedHashMap中,如果需要使用一个对象作为key, 要做get时,往往没办法保存当初put操作时的key object的reference,此时,需要让key object覆盖如下hashCode()和equals(Object obj)的实现。这样就可以通过containsKey 来判断是否包含此对象了。

package com.tian.menu.entity;


import android.util.Log;


public class MenuOrderInfoKey {
private int id;
private int status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getFlavor() {
return flavor;
}
public void setFlavor(int flavor) {
this.flavor = flavor;
}
private int flavor;
public MenuOrderInfoKey(int id,int status,int flavor)
{
this.id=id;
this.status=status;
this.flavor=flavor;
 
}
@Override
public int hashCode() {
 int ret = new Integer(id).hashCode() ^ new Integer(status).hashCode()^new Integer(this.flavor) ;
// 也可以用下面这种方式计算hashCode
//  int ret = String.valueOf(id).hashCode() ^ String.valueOf(type).hashCode();
 System.out.println(ret);
 return ret;
}

@Override
public boolean equals(Object o)
{
 
MenuOrderInfoKey k=(MenuOrderInfoKey)o;
//Log.d("meeeeeeeeeeee"+k.getId()+" status"+k.getStatus()+"fl"+k.getFlavor()," msg"+id+"status"+this.status+"ff"+this.flavor);
if(k.getId()!=this.id)
return false;
if(k.getStatus()!=this.status)
return false;
if(k.getFlavor()!=this.flavor)
return false;
return true; 

}
}

=============================================下面是添加新对象时判断是否已包含


public void addMenuInfo(MenuOrderInfo menuOrderInfo)
{
 
MenuOrderInfo current;
MenuOrderInfoKey key=new MenuOrderInfoKey(menuOrderInfo.getMenuinfo().getId(),menuOrderInfo.getStatus(),menuOrderInfo.getFlavor());
 
if(menulist.containsKey(key))
{
current=menulist.get(key);
current.setNum(menuOrderInfo.getNum()+current.getNum());
current.setChange_num(menuOrderInfo.getNum());
}else
{
menulist.put(key, menuOrderInfo);
}
 
}

你可能感兴趣的:(安卓开发,integer,object,equals,reference,class)