看代码注释吧!
public class Video {
/**
* @param args
*/
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList a1 = new ArrayList();
a1.add(new Person("lisi01", 11));
a1.add(new Person("lisi02", 12));
a1.add(new Person("lisi03", 13));
a1.add(new Person("lisi01", 11));
a1 = singleElement(a1);
Iterator it = a1.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();
sop(p.getName()+"----"+p.getAge());
}
}
public static ArrayList singleElement(ArrayList a1)
{
ArrayList newA1 = new ArrayList();
Iterator it = a1.iterator();
while(it.hasNext())
{
Person p = (Person) it.next();
//contains()这个方法内部调用的就是equals方法,所以Person类中要重写equals方法(比较姓名和年龄)
//equals方法如果不重写的话,比较的是对象的hashCode
if(!newA1.contains(p))
{
newA1.add(p);
sop("add :"+p.getName());
}
}
return newA1;
}
}
class Person
{
private String name;
private int age;
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
{
return false;
}
Person p = (Person)obj;
System.out.println(p.name+" : "+this.name);
//this表示调用该方法的对象,在上面的方法中调用contains方法是这样写的:newA1.contains(p)
//那么内部就是newAr1.equalsa(p),此时this=newAr1
return (this.name.equals(p.name)&&this.age==p.age);
}
Person(String name ,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
} |