- 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 ArrayListTest2
- {
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
-
- public static void main(String[] args)
- {
- ArrayList al=new ArrayList();
- al.add(new Person("lisi1",30));
- al.add(new Person("lisi2",32));
- al.add(new Person("lisi2",32));
- al.add(new Person("lisi3",33));
- al.add(new Person("lisi4",35));
- al.add(new Person("lisi4",35));
-
-
- al=singleElement(al);
-
- Iterator it=al.iterator();
-
- while(it.hasNext())
- {
- Person p=(Person)it.next();//要做强转的动作
- sop(p.getName()+"::"+p.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;
- }
- }
复制代码 大家好 我有一个小问题 就是关于Person类中复写了equals方法中的this,this到底是代表哪个对象呢?麻烦帮忙解答下,谢谢。
|
|