1. 程式人生 > >set去除重複物件

set去除重複物件

package setproject;
public class Person {
private String userName;
private String password;
private String address;

public Person(){}
public Person(String userName,String password,String address){
    this.userName=userName;
    this.password=password;
    this.address=address;
}

@Override  
public boolean equals(Object obj) {  
    if(obj == null) return false;  
    if(this == obj) return true;  
    if(obj instanceof Person){   
        Person message =(Person)obj;
        // 比較userName,password,address 一致時才返回true,之後再去比較 hashCode  
        if(message.userName == this.userName
           && message.password.equals(this.password)
           &&message.address.equals(this.address)) return true;  
        }  
          return false;  
 }  

@Override  
public int hashCode() {  
//重寫hashcode 方法,返回的hashCode 不一樣才認定為不同的物件
//return id.hashCode(); // 只比較id,id一樣就不新增進集合  
    return userName.hashCode() * password.hashCode()*address.hashCode();  
   }

}

測試用例如下:

public class SetDemo {
    @Test
    public void testDemo(){
        Set<Person> setPerson=new HashSet<Person>();
        setPerson.add(new Person("李白","123","濟南"));
        setPerson.add(new Person("李清照","456","山海關"));
        setPerson.add(new Person("李商隱","123","嘉峪關"));
        setPerson.add(new Person("李白","123","濟南"));
        setPerson.add(new Person("李白","456","濟南"));
        for(Iterator<Person> iter=setPerson.iterator();iter.hasNext();){
            Person person =iter.next();
            System.out.println("username:"+person.getUserName()+",password:"+person.getPassword()+",address:"+person.getAddress());
        }
    }
}

輸出的值如下:

"李白","123","濟南"

"李清照","456","山海關"

"李商隱","123","嘉峪關"

"李白","456","濟南"