import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Set set = new HashSet();
set.add(new String("abc"));
set.add(new Date());
set.add(new Integer(20));
set.add(null);
//添加自定义类型的对象,
Person p = new Person("10", "张三");
set.add(p);
//如果要表示重复,必须重写hashCode和equals方法
Person p2 = new Person("10", "张三");
set.add(p2);
System.out.println("p和p2相等吗?"+p.equals(p2));//true
}
}
class Person{
private String id;
private String name;
public Person(String id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(this == obj){ //是不是对象?
return true;
}
if(obj instanceof Person){ //是人这个对象吗?
Person person = (Person)obj; //传入的对象还原人类
if(this.id == person.id && this.name.equals(person.name)){
return true; //判断是否号码,名字,相等?对,回true;
}
}
return false;
}
@Override
public int hashCode() {
return id.hashCode(); //id是String类型的,回int类型调hashCode().
}//如果那个数是整型的,直接回那个值
}