本帖最后由 思维 于 2014-8-1 10:08 编辑
今天我将自定义对象人作为元素存到ArrayList集合中,并去除重复元素,同姓名同年龄视为一个人。(要求:必须使用ArrayList集合)。代码中总是遇到泛型的问题,今天终于解决了,正确代码如下:- import java.util.*;
- 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))
- return false;
- Person p=(Person)obj;
- return this.name.equals(p.name)&&this.age==p.age;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- }
- class ArrayListDemo{
- public static void main(String[] args){
- ArrayList<Person> al=new ArrayList<Person>();
- al.add(new Person("lisi01",31));
- al.add(new Person("lisi01",30));
- al.add(new Person("lisi02",32));
- al.add(new Person("lisi03",33));
- al.add(new Person("lisi01",30));
- SingleDemo<Person> sd=new SingleDemo<Person>();
- ArrayList<Person> all=sd.singleElement(al);
- Iterator<Person> it=all.iterator();
- while(it.hasNext()){
- Person p=(Person)it.next();
- System.out.println(p.getName()+"..."+p.getAge());
- }
- }
- }
- class SingleDemo<T>{
- public ArrayList<T> singleElement(ArrayList<T> al){
- ArrayList<T> newAl=new ArrayList<T>();
- Iterator<T> it=al.iterator();
- while(it.hasNext()){
- T t=it.next();
- if(!newAl.contains(t))
- newAl.add(t);
- }
- return newAl;
- }
- }
复制代码
|