将自定义对象作为元素存到ArrayList集合中,并去除重复元素
package jihe01;
public class Person {
private String name;
private int age;
public Person(String name,int age)//设置属性值
{
this.name=name;
this.age=age;
}
public String getName()//获取name值
{
return name;
}
public int getAge()//获取age值
{
return age;
}
//复写Object的Equals方法
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
return false;
Person p=(Person)obj;//强制将obj向下转型
return this.name.equals(p.getName()) && this.age==p.getAge();
}
}
package jihe01;
import java.util.ArrayList;
import java.util.Iterator;
/**
* 将自定义对象作为元素存到ArrayList集合中,并去除重复元素
* @author Administrator
*
*/
public class ArrayListTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stu
ArrayList al=new ArrayList();
al.add(new Person("zhangsan",25));
al.add(new Person("zhangsan",26));
al.add(new Person("zhangsan",25));
al.add(new Person("zhangsan",26));
al.add(new Person("zhangsan",27));
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 newal=new ArrayList();
Iterator it=al.iterator();
while(it.hasNext())
{
Object obj=it.next();
if(!newal.contains(obj))
newal.add(obj);
}
return newal;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
在ArrayListTest2类的singleElement方法中,明明没有条用Person类中的equals方法,为什么会成功去除Person对象中的重复元素?
帮忙说明一下函数底层的调用原理
|
|