本帖最后由 张然龙 于 2014-5-9 18:25 编辑
如注释所描述的 ,为什么取反就调用了Person中的equals方法,不取反就不会调用equals??
代码如下↓
- class Person
- {
- int age;
- String name;
- 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)
- {
- Person per=(Person)obj;
- System.out.println("进行了equals比较");//这个地方为什么一次都没读过?????
- return this.name.equals(per.getName())&&this.age==per.getAge();
- }
- }
- class Single
- {
- ArrayList<Person> al1=new ArrayList<Person>();
- public ArrayList<Person> method(ArrayList<Person> a)
- {
- for (Iterator<Person> it = a.iterator(); it.hasNext();)
- {
- Person per =(Person)it.next();
- if(al1.contains(per))//这个地方不用!取反,按理来说也会读到Person类中的覆盖方法equals的啊?
- {
- al1.add(per);
- }
- }
- return al1;
- }
- }
- class Demo4
- {
- public static void main(String[] args)
- {
- ArrayList<Person> al=new ArrayList<Person>();
- al.add(new Person("1",10));
- al.add(new Person("1",10));
- al.add(new Person("1",10));
- al.add(new Person("1",10));
- al.add(new Person("1",10));
- al=new Single().method(al);
- System.out.println(al);
- }
- }
复制代码 |