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


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


Java中的List接口的contains()方法用於檢查指定元素是否存在於給定列表中。

用法:

public boolean contains(Object obj)

object-element to be searched for

參數:此方法接受單個參數obj,其在列表中的存在將被測試。


返回值:如果在列表中找到指定的元素,則返回true,否則返回false。

下麵的程序在List中說明了contains()方法:

示例1:在整數列表中演示contains()方法的用法。

// Java code to demonstrate the working of 
// contains() method in List interface 
  
import java.util.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        // creating an Empty Integer List 
        List<Integer> arr = new ArrayList<Integer>(4); 
  
        // using add() to initialize values 
        // [1, 2, 3, 4] 
        arr.add(1); 
        arr.add(2); 
        arr.add(3); 
        arr.add(4); 
  
        // use contains() to check if the element 
        // 2 exits or not 
        boolean ans = arr.contains(2); 
  
        if (ans) 
            System.out.println("The list contains 2"); 
        else
            System.out.println("The list does not contains 2"); 
  
        // use contains() to check if the element 
        // 5 exits or not 
        ans = arr.contains(5); 
  
        if (ans) 
            System.out.println("The list contains 5"); 
        else
            System.out.println("The list does not contains 5"); 
    } 
}
輸出:
The list contains 2
The list does not contains 5

示例2:在字符串列表中演示方法contains()的工作。

// Java code to demonstrate the working of 
// contains() method in List of string 
  
import java.util.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        // creating an Empty String List 
        List<String> arr = new ArrayList<String>(4); 
  
        // using add() to initialize values 
        // ["geeks", "for", "geeks"] 
        arr.add("geeks"); 
        arr.add("for"); 
        arr.add("geeks"); 
  
        // use contains() to check if the element 
        // "geeks" exits or not 
        boolean ans = arr.contains("geeks"); 
  
        if (ans) 
            System.out.println("The list contains geeks"); 
        else
            System.out.println("The list does not contains geeks"); 
  
        // use contains() to check if the element 
        // "coding" exits or not 
        ans = arr.contains("coding"); 
  
        if (ans) 
            System.out.println("The list contains coding"); 
        else
            System.out.println("The list does not contains coding"); 
    } 
}
輸出:
The list contains geeks
The list does not contains coding

實際應用:在搜索操作中,我們可以檢查列表中是否存在給定元素。

參考: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)



相關用法


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