http://www.blogjava.net/apple0668/archive/2008/11/04/238721.html
最近重构项目里面的一个功能,其中用到Vector容器,有一种情况是Vector里面含有相同的元素,造成得到的结果不是预期的,所以要去掉Vector里面的重复的元素。
通过查看jdk文档,得知有个contains()方法,如果此向量包含指定的元素,则返回 true
。更确切地讲,当且仅当此向量至少包含一个满足 (o==null ? e==null : o.equals(e)) 的元素 e
时,返回 true
。
JDK原文:
contains
public boolean contains(Object elem)
-
Tests if the specified object is a component in this vector.
-
-
Specified by:
-
contains
in interfaceCollection<E>
Specified by:
-
contains
in interfaceList<E>
Overrides:
-
contains
in classAbstractCollection<E>
-
-
Parameters:
-
elem
- an object.
Returns:
-
true
if and only if the specified object is the same as a component in this vector, as determined by the equals method;false
otherwise. - 因此:可以通过该方法来实现过滤重复的元素。
contains方法JDK源码:
1
public
boolean
contains(Object elem)
{
2 return indexOf(elem, 0) >= 0;
3 }
2 return indexOf(elem, 0) >= 0;
3 }
1
public
synchronized
int
indexOf(Object elem,
int
index)
{
2 if (elem == null) {
3 for (int i = index ; i < elementCount ; i++)
4 if (elementData[i]==null)
5 return i;
6 } else {
7 for (int i = index ; i < elementCount ; i++)
8 if (elem.equals(elementData[i]))
9 return i;
10 }
11 return -1;
12 }
2 if (elem == null) {
3 for (int i = index ; i < elementCount ; i++)
4 if (elementData[i]==null)
5 return i;
6 } else {
7 for (int i = index ; i < elementCount ; i++)
8 if (elem.equals(elementData[i]))
9 return i;
10 }
11 return -1;
12 }
注:contains方法里面返回的indexOf(Object elem, int index)方法,十分重要。
测试例子:
1
package
org.apple.collection.test;
2
3 import java.util.Vector;
4
5 public class VectorTest {
6
7 /** *//**
8 * @param args
9 */
10 public static void main(String[] args) {
11 // TODO Auto-generated method stub
12 Vector<String> v = new Vector<String>();
13 Vector<String> o = new Vector<String>();
14 v.add("aaaaa");
15 v.add("bbbbb");
16 v.add("aaaaa");
17 v.add("ccccc");
18 for(int i=0;i<v.size();i++)
19 {
20 if(!o.contains(v.get(i)))
21 o.add(v.get(i));
22 }
23 for(int j = 0;j<o.size();j++)
24 {
25 System.out.println(o.get(j));
26 }
27
28 }
29
30}
31
2
3 import java.util.Vector;
4
5 public class VectorTest {
6
7 /** *//**
8 * @param args
9 */
10 public static void main(String[] args) {
11 // TODO Auto-generated method stub
12 Vector<String> v = new Vector<String>();
13 Vector<String> o = new Vector<String>();
14 v.add("aaaaa");
15 v.add("bbbbb");
16 v.add("aaaaa");
17 v.add("ccccc");
18 for(int i=0;i<v.size();i++)
19 {
20 if(!o.contains(v.get(i)))
21 o.add(v.get(i));
22 }
23 for(int j = 0;j<o.size();j++)
24 {
25 System.out.println(o.get(j));
26 }
27
28 }
29
30}
31
输出结果aaaaa bbbbb ccccc
PS:所以通过contains方法可以把重复元素过滤掉。