- /*用ArrayList来添加删除自定义的对象 并且容器里无重复对象
- */
- import java.util.*;
- class Person
- {String name;
- int age;
- Person(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)//重写Object类的equals方法来判断两个对象是否相等
- {if (!(obj instanceof Person))
- return false;
- Person p=(Person)obj;
- return this.name.equals(p.name)&& this.age==p.age;
- }
- }
- class ArrayTest2
- {public static void main(String[] args)
- {ArrayList al=new ArrayList(); //Collections里面一个实例
- al.add(new Person("lisi01",30));//向容器里添加元素
- al.add(new Person("lisi02",32));
- al.add(new Person("lisi02",32));
- al.add(new Person("lisi03",33));
- al.add(new Person("lisi04",34));
- al.add(new Person("lisi04",34));
-
- al=singleElement(al);
- // sop(al.remove(new Person("lisi02",32)));//在删除之前会先调用equals方法
- Iterator it=al.iterator();//创建一个迭代器,以便用来遍历容器中元素
-
- while(it.hasNext())//循环遍历容器中的元素
- {Object obj=it.next();
- Person p=(Person)obj;
- sop(p.getName()+"...."+p.getAge());
- }
- }
- public static void sop(Object obj)
- {System.out.println(obj);
- }
- 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;
- }
- }
复制代码 希望对楼主有所帮助 |