- package First;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import bean.Person;
public class Dream {
public static void main(String args[])
{
LinkedHashSet h1=new LinkedHashSet();
h1.add(new Person("xiao1",1));
h1.add(new Person("xiao3",3));
h1.add(new Person("xiao2",2));
h1.add(new Person("xiao3",3));
Iterator it=h1.iterator();
while(it.hasNext())
{
Person p=(Person) it.next();
System.out.println(p.getName()+".."+p.getAge());
}
}
}
package bean;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
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;
}
public boolean equals(Object obj)
{
Person p=(Person)obj;
return this.name.equals(p.name) && this.age==p.age;
}
}
看不懂person类重写的equals方法。请详细讲解一下,还有就是在执行h1.add(new Person("xiao1",1));这种代码时,谁去调用了hashcode()和equals()?过程讲解一下.最大的疑惑在于equals方法中obj只和调用equals方法的对象做了对比,不是只有一次吗?只能判断出一个对象不与其重复吗?