/*
ArrayList练习2:
存储一个人类,姓名、年龄相同则视为同一个人。
去除同一个元素
*/
import java.util.*;
class Man
{
private String name;
private int age;
Man(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public boolean equals(Object obj)//复写的equals方法:
{
if(!(obj instanceof Man))
return false;
Man m=(Man)obj;
return this.name.equals(m.name)&&this.age==m.age;
}
}
class DelArray2
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(new Man("zhangsan",13));
al.add(new Man("zhangsan",13));
al.add(new Man("lisi",16));
al.add(new Man("lisi",16));
Iterator it=al.iterator();
while (it.hasNext())
{
Man m=(Man)it.next();
System.out.println(m.getName()+"...."+m.getAge());
}
singleElement(al);
for(Object obj:al)
{
Man m=(Man)obj;
System.out.println(m.getName()+"...."+m.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;
}
}
复写了Man类中的equals方法,为什么运行结果没有将重复的元素去除?
去除前:
zhangsan....13
zhangsan....13
lisi....16
lisi....16
去除后:
zhangsan....13
zhangsan....13
lisi....16
lisi....16
请按任意键继续. . .
|
|