Java 中的 contains(obj o) 方法的作用是什么?


java.util.ArrayList 类contains(Object) 方法在该列表包含指定元素时返回 true。

示例

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
      arrlist.add(20);
      arrlist.add(25);
      arrlist.add(10);
      arrlist.add(15);
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }
      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");
      }
      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

更新于: 2020-02-25

86 次浏览

开创你的 职业生涯

完成课程获得认证

开始吧
广告