`
aijuans
  • 浏览: 1547242 次
社区版块
存档分类
最新评论

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

 
阅读更多

题目:

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
思路
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);
        }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
    }

 

欢迎大家访问我的个人网站 萌萌的IT人
3
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics