创建hashSet对象为什么会自动调用他的普通方法
import java.util.*;public class HashSetText {
public static void main(String [] args)
{
HashSet hs = new HashSet();
hs.add(new Person("a1", 11)); →→ 为什么创建一个对象会自动调用类中的普通方法、创建对象调用其构造方法能理解,能自动调用普通
hs.add(new Person("a2", 12)); 就不能理解了
hs.add(new Person("a3", 13));
hs.add(new Person("a2", 12));
Iterator a = hs.iterator();
while(a.hasNext())
{
System.out.println(a.next());
}
}
}
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public int hashCode()//重写了hascode 和 equals 方法;
{
System.out.println(this.name + "..>><<...hasCode");
return 100;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
{
return false;
}
Person p = (Person) obj;
System.out.println(this.name +"..equals..."+ p.name);
return this.name.equals(p.name) && this.age == (p.age);
}
}