import java.util.*;
class ArrayListDemo
{
public static void main(String[] a)
{
ArrayList ali = new ArrayList();
ali.add(new Person("abc1",21));
ali.add(new Person("abc2",22));
ali.add(new Person("abc2",22));
ali.add(new Person("abc2",22));
ali.add(new Person("abc1",21));
ali.add(new Person("abc1",21));
ali.add(new Person("abc2",22));
ali.add(new Person("abc1",21));
ali.add(new Person("abc2",22));
System.out.println(ali);
ali=getSingleElement(ali);
System.out.println(ali);
}
public static ArrayList getSingleElement(ArrayList ali)
{
ArrayList temp = new ArrayList();
Iterator it = ali.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(!temp.contains(obj))
temp.add(obj);
}
return temp;
}
}
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+"::"+age;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
throw new ClassCastException("类型不匹配");
Person p=(Person)obj;
return this.name.equals(p.name) && this.age==p.age; //为什么这里这么写啊 name.equals(p.name) 和 age==p.age 比较的是?
}
} |