Java.util.ArrayList.contains() 方法

描述

如果此列表包含指定的元素,java.util.ArrayList.contains(Object) 方法返回 true。


声明

以下是 java.util.ArrayList.contains() 方法的声明

public boolean contains(Object o)

参数

o − 要测试在此列表中是否存在的元素。


返回值

如果此列表包含指定元素,则此方法返回 true。


异常

NA


示例

下面的例子展示了 java.util.Arraylist.contains 方法的使用。

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      
      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(8);

      // use add() method to add elements in the list
      arrlist.add(20);
      arrlist.add(25);
      arrlist.add(10);
      arrlist.add(15);        
          
      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }

      // list contains element 10
      boolean retval = arrlist.contains(10); 
        
      if (retval == true) {
         System.out.println("element 10 is contained in the list");
      } else {
         System.out.println("element 10 is not contained in the list");
      }
         
      // list does not contain element 30
      boolean retval2 = arrlist.contains(30);
        
      if (retval2 == true) {
         System.out.println("element 30 is contained in the list");
      } else {
         System.out.println("element 30 is not contained in the list");    
      }
   }
}

让我们编译并运行上面的程序,这将产生以下结果 −

Number = 20
Number = 25
Number = 10
Number = 15
element 10 is contained in the list
element 30 is not contained in the list