import java.util.*;
class acc1
{
private String name;
private int age;
acc1(String name,int age)
{
this.name=name;
this.age=age;
}
public boolean equals(Object obj)
{
if(!(obj instanceof acc1))
return false;
acc1 p=(acc1)obj;
return this.name.equals(p.name) && this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
public class acc
{
public static void main(String argv[])
{
ArrayList al=new ArrayList();
al.add(new acc1("zhangsan",19));
al.add(new acc1("lisi",20));
al.add(new acc1("wangwu",21));
al.add(new acc1("wangwu",21));
al=singleElement(al);
//控制输出的部分
Iterator it=al.iterator();
while(it.hasNext())
{
acc1 p=(acc1)it.next();//在这里为什么要进行类型转换呢?
sop(p.getName()+"::"+p.getAge());
}
}
public static ArrayList singleElement(ArrayList al)
{
ArrayList newal=new ArrayList();
Iterator it=al.iterator();
while(it.hasNext())
{
Object obj=it.next();
if(!newal.contains(obj))//contains方法的所谓底层调用是怎么回事?
newal.add(obj);
}
return newal;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
上面程序的两个问题该怎么理解? |