检查Java ArrayList是否包含给定项
java.util.ArrayList.contains()方法可用于检查JavaArrayList是否包含给定项。此方法具有单个参数,即测试了其在ArrayList中是否存在的项目。如果该项目在ArrayList中存在,则返回true;如果不存在,则返回false。
演示此的程序如下所示-
示例
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");
if(aList.contains("C"))
System.out.println("The element C is available in the ArrayList");
else
System.out.println("The element C is not available in the ArrayList");
if(aList.contains("H"))
System.out.println("The element H is available in the ArrayList");
else
System.out.println("The element H is not available in the ArrayList");
}
}输出结果
The element C is available in the ArrayList The element H is not available in the ArrayList
现在让我们了解上面的程序。
创建ArrayListaList。然后,使用ArrayList.add()将元素添加到ArrayList中。ArrayList.contains()用于检查“C”和“H”在ArrayList中是否可用。然后使用if语句打印它们是否可用。演示这的代码片段如下-
List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");
if(aList.contains("C"))
System.out.println("The element C is available in the ArrayList");
else
System.out.println("The element C is not available in the ArrayList");
if(aList.contains("H"))
System.out.println("The element H is available in the ArrayList");
else
System.out.println("The element H is not available in the ArrayList");热门推荐
10 高中升学宴祝福语简短
11 对别人新年祝福语简短
12 开业祝福语简短大气的
13 关于早晨的祝福语简短
14 送给情侣贺卡祝福语简短
15 简短古文生日祝福语
16 亲姐姐怀孕祝福语简短
17 春节拜年祝福语儿童简短
18 祝福语生日男朋友简短