日期:2014-05-20  浏览次数:20971 次

set集合如何去除重复的对象
面试的时候碰到这样一个问题,不太明白
Java code

User u1 = new User();
u1.name="aa";
u1.password = "11";
User u2 = new User();
u2.name = "bb";
u2.password = "22";
Set sets = new HashSet();
sets.add(u1);
sets.add(u2);


是类似这样的去重复吗?

------解决方案--------------------
Java code

public class User{

  @Override
  public String toString(){
    return this.name;
  }

  @Override String hashCode(){
    return User.class.toString()+toString();
  }

  @Override boolean equals(Object object){
    if(object==null) return this==null;
    return object.toString().equals(toString());
  }
}

------解决方案--------------------
上面给出了部分代码,现在给出set的全部代码,中间有代码的验证部分。试验结果是
1
[Name :bb Password:22]

Java code

 import java.util.*;
public class TestSet {
    public static void main(String[] args) {
        User u1 = new User("aa","11");
         
        User u2 = new User("bb","22");
        Set sets = new HashSet();
        sets.add(u1);
        sets.add(u2);
        sets.remove(u1);//删除点一个User对象,然后进行验证  试验结果成功
        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;
    }
    public boolean equals(Object obj){
         if(obj instanceof User){
         User user=(User)obj;
         return (name.equals(user.name))&&(password.equals(user.password));
         }
         return super.equals(obj);
     }
     public int hashCode(){
         return name.hashCode();
     }
}