蓝少泽

天生我材必有用,千金散去还复来。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java语言中,比较两个Object是否相等,需重写equal()方法和hasCode()方法

public class UserHistory implements Serializable{

    private static final long serialVersionUID = 1L;
    


    public UserHistory(String content) {
        super();
        this.content = content;
        this.id = id;
    }

    private String content;
    private String id;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    
    @Override
    public boolean equals(Object o) {
        if(o instanceof UserHistory){
            UserHistory h = (UserHistory) o;
            if(h.content!=null && h.content.equals(this.content)){
                return true;
            }
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        return content.hashCode();
    }
    


    
    
}
userHistory = new UserHistory(text);
SearchHistoryDao searchHistoryDao = new SearchHistoryDao(context);
if(!findAllUserHistory.contains(userHistory)){
    searchHistoryDao.insertUserHistory(userHistory);
}

之后就可以根据List<Object> 的contain(SubClass)来判断两个对象是否相等。

posted on 2013-06-05 13:53  蓝少泽  阅读(341)  评论(0编辑  收藏  举报