- package com.leo.blog;
- import java.util.*;
- class Human
- {
- private String name;
- private int age;
- Human(String name,int age)
- {
- this.age = age;
- this.name = name;
- }
- public boolean equals(Object obj)
- {
- if(obj instanceof Human)
- return false;
- Human h = (Human) obj;
- return this.name.equals(h.name)&&this.age==h.age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- class ArrayListTest {
-
- public static void main(String[] args) {
-
- ArrayList al = new ArrayList();
- al.add(new Human("LEO",25));
- al.add(new Human("LAY",24));
- al.add(new Human("KOBE",36));
- al.add(new Human("PAUL",35));
- System.out.println(al);
- System.out.println(singleElement(al));
-
- }
- 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))//这里调用了一下contains就调用了equals方法这里有点不明白
- {
- newAl.add(obj);
- }
- }
- return newAl;
- }
- }
复制代码
if(!newAl.contains(obj))//这里调用了一下contains就调用了equals方法这里有点不明白毕老师在讲这里的时候说是调用了contains方法就调用了equals,但是查阅了api也没发现有哪里有调用,麻烦讲解一下~谢过~~
|