package com.jiyun;
import java.util.HashSet;
public class Test1 {
public static void main(String[] args) {
HashSet hs=new HashSet();
Person p=new Person("张三", 21);
hs.add(p);
p.setName("李四");
p.setAge(22);
hs.add(p);
System.out.println(hs);
}
}
class Person{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int hashCode()
{
return name.hashCode()+age*21;
}
public boolean equals(Object obj)
{
if(obj instanceof Person)
{
Person p=(Person)obj;
return name.equals(p.getName())&&age==p.getAge();
}
else{
return false;
}
}
public String toString()
{
return name+"--"+age;
}
}
输出结果为:[李四--22, 李四--22] 为什么
|
|