以前总觉得java类对象很简单,但是今天的一个同事的点播,让我对java的对象有了不一样的理解,下面我来介绍一下equals()和hashCode()的用法:

先粘一段代码:

public class TestAdd {

        public static void main(String[] args) {
            User u1 = new User("aa","11");
              
            User u2 = new User("aa","11");
            Set<User> sets = new HashSet<User>();
            sets.add(u1);
            sets.add(u2);
           
            System.out.println(sets.size());
            System.out.println(sets);
        }
}

class User{
    String name;
    String password;
    User(String name,String password){
        this.name=name;
        this.password=password;
    }
    public String toString(){
        return "Name :"+name+"  "+"Password:"+password;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result
                + ((password == null) ? 0 : password.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (password == null) {
            if (other.password != null)
                return false;
        } else if (!password.equals(other.password))
            return false;
        return true;
    }
    
}

equals()方法使用来判断其他对象和当前对象是否相等

hashCode()方法是给对象返回一个hashCode值

注:在set集合中,实现对象的去重方法,只需要在User对象中重载equals()和hashCode()函数,在set集合内部会自动是去重。

了解更多set内部去重的问题,请参考http://www.cnblogs.com/Qian123/p/5703507.html

posted on 2017-03-29 14:55  C碧水蓝天S  阅读(321)  评论(0编辑  收藏  举报