本帖最后由 18353666072 于 2014-6-20 20:09 编辑
- 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 ArrayListEx
- {
- 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",33));
- al.add(new person("lisi04",35));
- al.add(new person("lisi05",38));
- al.add(new person("lisi05",38));
-
- al=singleElement(al);
- Iterator it = al.iterator();
- while(it.hasNext())
- {
- /*Object obj = it.next();
- person p = (person)obj;
- */
- 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;
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码
1 : return this.name.equals(p.name) && this.age == p.age;这句话怎么理解
2 :this.name是new person();的么
3 :p.name是equals的么,4 :return this.name.equals(p.name) && this.age == p.age 为什么name的比较用的是equals(他们是对象比较么,对象比较都用equals么,),而age比较用的是== (这里是不叫的值对吧)。。。。
|
|