检查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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短