随笔-61  评论-159  文章-0  trackbacks-0
        最近重构项目里面的一个功能,其中用到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 interface Collection<E>
Specified by:
contains in interface List<E>
Overrides:
contains in class AbstractCollection<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源码:

 

1public boolean contains(Object elem) {
2    return indexOf(elem, 0>= 0;
3    }

 

 1public 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    }

注:contains方法里面返回的indexOf(Object elem, int index)方法,十分重要。

测试例子:

 1package org.apple.collection.test;
 2
 3import java.util.Vector;
 4
 5public 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方法可以把重复元素过滤掉。

 




-------------------------------------------------------------------------------------------------
PS:本博客文章,如果没有注明是有“转”字样,属于本人原创。如果需要转载,务必注明作者文章的详细出处地址,否则不允许转载,多谢合作!
posted on 2008-11-04 23:48 apple0668 阅读(3933) 评论(0)  编辑  收藏 所属分类: java

只有注册用户登录后才能发表评论。


网站导航: