检查Java ArrayList是否包含给定项
java.util.ArrayList.contains()方法可用于检查Java ArrayList是否包含给定项。此方法具有单个参数,即测试了其在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 ArrayListThe element H is not available in the ArrayList
现在让我们了解上面的程序。
创建ArrayList aList。然后,使用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");
以上是 检查Java ArrayList是否包含给定项 的全部内容, 来源链接: utcz.com/z/357020.html