第二遍
- import java.util.*;
- /* 练习: 将自定义对象作为元素存到ArrayList集合中,并去除重复元素.
- 思路:
- 1,对人描述,将数据封装进人对象;
- 2,定义容器,将人存入;
- 3,取出.
- */
- public class ArrayListTest {
- public static void main(String[] args) {
-
- ArrayList al = new ArrayList();
-
- al.add(new Person("Shawn01",31));
- al.add(new Person("Shawn02",32));
- al.add(new Person("Shawn02",32));
- al.add(new Person("Shawn03",33));
- al.add(new Person("Shawn04",34));
- al.add(new Person("Shawn04",34));
- al.add(new Person("Shawn05",35));
-
- al = singleElement(al);
-
- for(Iterator it = al.iterator(); it.hasNext(); ) {
-
- Person p = (Person)it.next();//避免iterator指针跳跃,同时强转Object为Person
- System.out.println("name=" + p.getName() + ", age=" + p.getAge());
- }
-
-
- }
-
- private static ArrayList singleElement(ArrayList al) {
-
- ArrayList newAl = new ArrayList();
-
- for(Iterator it = al.iterator(); it.hasNext(); ) {
-
- Object o = it.next();
-
- if(!newAl.contains(o)) {
-
- newAl.add(o);
- }
- }
- return newAl;
- }
- }
- class Person {
- private String name;
- private int age;
-
- public Person(String name, int age) {
-
- this.name = name;
- this.age = age;
- }
- /*
- public void setName(String name) {
-
- this.name = name;
- }
-
- public void setAge(int age) {
-
- this.age = age;
- }
- */
- public String getName() {
-
- return name;
- }
-
- public int getAge() {
-
- return age;
- }
-
- public boolean equals(Object obj) {
-
- if(!(obj instanceof Person))
- return false;
-
- Person p = (Person)obj;
- return name.equals(p.name) && this.age == p.age;
-
- }
- }
复制代码 |