import java.util.HashSet;
import java.util.Set;
class PersonDemo{
private String name;
public PersonDemo(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "name= " + name ;
}
//没有覆写hashcode和equals方法前,显示三次(一样的)。覆写后,只剩下一个了!说明覆写后方法起作用了,重复的输入不进去!
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PersonDemo other = (PersonDemo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
public class Demo12 {
public static void main(String[] args) {
Set s = new HashSet();
s.add(new PersonDemo("章泽天"));
s.add(new PersonDemo("章泽天"));
s.add(new PersonDemo("章泽天"));
System.out.println(s);
}
} |
|