通過查看jdk文檔,得知有個(gè)contains()方法,如果此向量包含指定的元素,則返回
true
。更確切地講,當(dāng)且僅當(dāng)此向量至少包含一個(gè)滿足 (o==null ? e==null : o.equals(e)) 的元素 e
時(shí),返回 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.- 因此:可以通過該方法來實(shí)現(xiàn)過濾重復(fù)的元素。
contains方法JDK源碼:
1public boolean contains(Object elem) {
2return indexOf(elem, 0) >= 0;
3}
1public synchronized int indexOf(Object elem, int index) {
2if (elem == null) {
3for (int i = index ; i < elementCount ; i++)
4if (elementData[i]==null)
5return i;
6} else {
7for (int i = index ; i < elementCount ; i++)
8if (elem.equals(elementData[i]))
9return i;
10}
11return -1;
12}
注:contains方法里面返回的indexOf(Object elem, int index)方法,十分重要。
測試?yán)樱?br />
1package org.apple.collection.test;
2
3import java.util.Vector;
4
5public class VectorTest {
6
7/**
8* @param args
9*/
10public static void main(String[] args) {
11// TODO Auto-generated method stub
12Vector<String> v = new Vector<String>();
13Vector<String> o = new Vector<String>();
14v.add("aaaaa");
15v.add("bbbbb");
16v.add("aaaaa");
17v.add("ccccc");
18for(int i=0;i<v.size();i++)
19{
20if(!o.contains(v.get(i)))
21o.add(v.get(i));
22}
23for(int j = 0;j<o.size();j++)
24{
25System.out.println(o.get(j));
26}
27
28}
29
30}
31輸出結(jié)果aaaaa bbbbb ccccc
PS:所以通過contains方法可以把重復(fù)元素過濾掉。
-------------------------------------------------------------------------------------------------
PS:本博客文章,如果沒有注明是有“轉(zhuǎn)”字樣,屬于本人原創(chuàng)。如果需要轉(zhuǎn)載,務(wù)必注明作者和文章的詳細(xì)出處地址,否則不允許轉(zhuǎn)載,多謝合作!