首页 > 代码库 > ArrayList的contains方法,底层调用了equals方法。

ArrayList的contains方法,底层调用了equals方法。

题目:

将自定义对象作为元素存到ArrayList集合中,并去除重复元素

比如:存人对象,同姓名,同年龄,视为同一个人,为重复元素。

/*
思路
1对人描述,将数据封装进人对象
2定义容器,将人存入
3取出
*/
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 Test
{
        public static void main(String[] args)
        {
                ArrayList al = new ArrayList();

                al.add(new Person("lisi01",30));
                al.add(new Person("lisi02",35));
                al.add(new Person("lisi03",32));
                al.add(new Person("lisi02",35));
                al.add(new Person("lisi03",32));
                al.add(new Person("lisi04",31));

                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;
        }

        public static void sop(Object obj)
        {
                System.out.println(obj);
        }
}
public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))    //调用参数的equals方法
                    return i;
        }
        return -1;
    }


ArrayList的contains方法,底层调用了equals方法。