1. 程式人生 > >HashSet去重

HashSet去重

編寫類Person有兩個屬性id,name。利用HashSet類對此類的多個物件以id進行排重。

package com.cc;



import java.util.HashSet;


public class Hello{
public static void main(String[] args) {
HashSet<Person> set = new HashSet<Person>();
set.add(new Person("1", "hehe"));
System.out.println(set.contains(new Person("1", "hehe")));
}
}
//實體
class Person{
private String id;
private String name;
public Person(String id,String name){
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
System.out.println(id.hashCode());
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;
}
if(obj.getClass() == Person.class){
Person p = (Person) obj;
return p.id.equals(id);//根據比較id
}
return false;
}
}