Java中的Vector contains()方法

Java中的Vector contains()方法

java.util.vector.contains() 方法用于检查向量中是否存在特定元素。所以基本上它用于检查向量是否包含任何特定的元素。 语法:

Vector.contains(Object element)

参数: 此方法需要一个强制性参数 element,它是向量类型。这是需要测试它是否在向量中出现的元素。

返回值: 如果该元素在向量中,则此方法返回 ,否则返回 。下面的程序说明了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

时间复杂度: O(n),其中n是向量中的元素个数。

辅助空间: O(n)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程