Java中的 Vector contains() 方法
Java.util.vector.contains()方法用于检查向量中是否存在特定元素。所以基本上它用于检查向量是否包含任何特定元素。
句法:
Vector.contains(Object element)
参数:此方法采用向量类型的强制参数元素。这是需要测试的元素是否存在于向量中。
返回值:如果元素存在于向量中,则此方法返回True ,否则返回False 。
下面的程序说明了Java.util.Vector.contains() 方法:
方案一:
// Java code to illustrate contains()
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
// Creating an empty Vector
Vector vec_tor = new Vector();
// 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
方案二:
// Java code to illustrate contains()
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
// Creating an empty Vector
Vector vec_tor = new Vector();
// 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