黑马程序员技术交流社区
标题:
将自定义对象作为元素存储到ArrayList集合中,并去除重复...
[打印本页]
作者:
1017161726
时间:
2015-5-2 11:33
标题:
将自定义对象作为元素存储到ArrayList集合中,并去除重复...
/*
将自定义对象作为元素存储到ArrayList集合中,并去除重复元素。
*/
老师讲的比较快,自己琢磨好久才写出来。
import java.util.*;
class Demo8
{
public static void main(String [] args)
{
ArrayList al=new ArrayList();
al.add(new Person("L1",22)); //al.add(Object oo); 存进去的对象是Object类型。取出时应向下转型。
al.add(new Person("L2",26));
al.add(new Person("L3",30));
al.add(new Person("L3",30)); //new两个相同的元素,存到不同的地址。去重复方法不管用。需要重写equals方法。
al.add(new Person("L4",28));
al=noRepeat(al);
Iterator it=al.iterator();
while (it.hasNext())
{
Person p=(Person)it.next(); //向下转型。
System.out.println(p.getName()+"::::"+p.getAge());
}
}
public static ArrayList noRepeat(ArrayList al) //去重复方法。
{
ArrayList temp=new ArrayList();
Iterator it=al.iterator();
while (it.hasNext())
{
Object oo=it.next();
if (!temp.contains(oo))
temp.add(oo);
}
return temp;
}
}
class Person
{
private String name;
private int age;
Person (String name,int age)
{
this.name=name;
this.age=age;
}
public boolean equals(Object oo) //重写equals方法。
{
if (!(oo instanceof Person))
return false;
Person p=(Person)oo;
//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;
}
}
复制代码
作者:
许庭洲
时间:
2015-5-2 20:05
值得学习ing!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2