當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Vector contains()用法及代碼示例


java.util.vector.contains()方法用於檢查Vector中是否存在特定元素。因此,本質上,它用於檢查向量是否包含任何特定元素。

用法:

Vector.contains(Object element)

參數:此方法采用矢量類型的必需參數element 。無論是否存在於載體中,這都是需要測試的元素。


返回值:如果向量中存在元素,則此方法返回True,否則返回False。

以下示例程序旨在說明Java.util.Vector.contains()方法:

示例1:

// Java code to illustrate contains() 
import java.util.*; 
  
public class VectorDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Vector 
        Vector<String> vec_tor = new Vector<String>(); 
  
        // Use add() method to add elements into the Vector 
        vec_tor.add("Welcome"); 
        vec_tor.add("To"); 
        vec_tor.add("Geeks"); 
        vec_tor.add("4"); 
        vec_tor.add("Geeks"); 
  
        // Displaying the Vector 
        System.out.println("Vector: " + vec_tor); 
  
        // Check for "Geeks" in the Vector 
        System.out.println("Does the vector contains 'Geeks'? "
                           + vec_tor.contains("Geeks")); 
  
        // Check for "4" in the Vector 
        System.out.println("Does the Vector contains '4'? "
                           + vec_tor.contains("4")); 
  
        // Check if the Queue contains "No" 
        System.out.println("Does the Queue contains 'No'? "
                           + vec_tor.contains("No")); 
    } 
}
輸出:
Vector: [Welcome, To, Geeks, 4, Geeks]
Does the vector contains 'Geeks'? true
Does the Vector contains '4'? true
Does the Queue contains 'No'? false

示例2:

// Java code to illustrate contains() 
import java.util.*; 
  
public class VectorDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Vector 
        Vector<Integer> vec_tor = new Vector<Integer>(); 
  
        // Use add() method to add elements into the Vector 
        vec_tor.add(10); 
        vec_tor.add(15); 
        vec_tor.add(30); 
        vec_tor.add(20); 
        vec_tor.add(5); 
  
        // Displaying the Vector 
        System.out.println("Vector: " + vec_tor); 
  
        // Check for "Geeks" in the Vector 
        System.out.println("Does the vector contains 'Geeks'? "
                           + vec_tor.contains("Geeks")); 
  
        // Check for "4" in the Vector 
        System.out.println("Does the Vector contains '4'? "
                           + vec_tor.contains("4")); 
  
        // Check if the vector contains "No" 
        System.out.println("Does the Vector contains 'No'? "
                           + vec_tor.contains("No")); 
    } 
}
輸出:
Vector: [10, 15, 30, 20, 5]
Does the vector contains 'Geeks'? false
Does the Vector contains '4'? false
Does the Vector contains 'No'? false


相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 Vector contains() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。