java初学者,对hashcode和equals方法了解还不多
要求是当name相同时,hashcode返回值相同,equals返回true
```java
class person{
private String name;
private int age;
String getname() {
return this.name;
}
person(String s,int a){
this.name=s;
this.age=a;
}
public boolean equals(Object o) {
if(this==o) {
return true;
}
if(!(o instanceof person)) {
return false;
}
person t=(person)o;
return t.name.equals(this.name);
}
public int hashcode() {
return Objects.hash(getname());
}
}
public static void main(String[] args) {
HashSet<person> hs=new HashSet<person>();
hs.add(new person("张三", 18));
hs.add(new person("petr", 30));
hs.add(new person("张三", 20));
Iterator<person> it=hs.iterator();
while(it.hasNext()) {
System.out.println(it.next().getname());
}
```