存储人的年龄姓名到数据集合中,同名同年龄视为一人,不进行存储,但是代码中contains不自动调用复写的equals方法,所以同名同年龄的不会被去除怎么回事,求帮助,谢谢!
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;
System.out.println("bbbbb");
Person p=(Person)obj;//向下转型
return this.name.equals(p.name)&&this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
public class Test5
{
public static void main(String [] args)
{
ArrayList al=new ArrayList();
al.add(new Person("zhangsan",30));
al.add(new Person("lisi1",30));
al.add(new Person("lisi2",20));
al.add(new Person("wangwu",40));
al.add(new Person("lisi2",20));
al=singleElement(al);
Iterator it=al.iterator();
while (it.hasNext())
{
Person p=(Person)it.next();
sop(p.getName()+"::"+p.getAge());
}
}
public static ArrayList singleElement(ArrayList al)//去除重复元素
{
ArrayList al1=new ArrayList();
System.out.println("aaaaaa");
Iterator it=al.iterator();
while(it.hasNext())
{
Object obj=it.next();
if(!al1.contains(obj))
al1.add(obj);
}
return al1;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
|
|