- 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; //this为什么不用进行类型提升
- }
-
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class ArrayListTest
- {
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- public static void main(String args[])
- {
- ArrayList al= new ArrayList();
- al.add(new Person("lisi01",30));
- al.add(new Person("lisi02",32));
- al.add(new Person("lisi02",32));
- al.add(new Person("lisi03",35));
- al.add(new Person("lisi04",33));
-
- al=singelElement(al);
-
- Iterator it =al.iterator();
- while(it.hasNext())
- {
- Person p=(Person)it.next();
- sop(p.getName()+"..."+p.getAge());
- }
- }
- public static ArrayList singelElement(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;
-
- }
- }
复制代码 本题是老师视频的例题,我的问题是关于 contains方法的,查阅API知道public boolean contains(Object o)中实际是 (o==null ? e==null : o.equals(e)),就是说程序中的if(!newal.contains(obj))中的obj就是调用的是obj.equals(e),在Person类中public boolean equals(Object obj),这里的equals(Object obj)中的Object obj是API中的e,可是调用者this也是obj类型啊,为什么this不用提升就可以使用this.name呢??? |