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))//判断obj是否是person实例
return false;
Person p = (Person)obj;//向下强转,以便于调用person特有方法
//System.out.println(this.name+"....."+p.name);
return this.name.equals(p.name) && this.age == p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class ArrayListTest2
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Demo());
al.add(new Person("lisi01",30));//al.add(Object obj);//Object obj = new Person("lisi01",30);
al.add(new Person("lisi02",32));
al.add(new Person("lisi02",32));
al.add(new Person("lisi04",35));
al.add(new Person("lisi03",33));
al.add(new Person("lisi04",35));
al = singleElement(al);①
//sop("remove 03 :"+al.remove(new Person("lisi03",33)));//remove方法底层也是依赖于元素的equals方法。
for (Iterator it = al.iterator(); 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);
}
}
我上面标注的理解大致运行过程对么?contains 自动调用equals方法?为什么?
|