import java.util.*;
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
System.out.println(this.name+"======="+p.name);
return this.name.equals(p.name) && this.age == p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class Noname9
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Person("zhangsan01",31));
al.add(new Person("zhangsan01",31));
al.add(new Person("zhangsan03",32));
al.add(new Person("zhangsan05",34));
al.add(new Person("zhangsan05",34));
Iterator it = al.iterator();
while(it.hasNext())
{
Person p = (Person) it.next();
sop("name: "+p.getName()+"--"+"age: "+p.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
要实现的功能为:当向ArrayList中添加Person对象的时候,调用Person类中的equals方法,将name和age一样的对象,认为是相同的对象,在ArrayList只存储一个,保证里面没有重复对象,
但是结果却是
全部都添加进出了
这是为什么呢? |