有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中检查整个ArrayList

我有一个简单的想法,但我不知道如何正确地实施它。。。 交易如下:

假设有一个名为myList的数组列表,大小为5,然后是 一个称为testNumber的整数。myList和/或testNumber中的值不相关

我需要做的是将testNumber变量与myList的每个整数进行比较 如果testNumber不等于它们中的任何一个,则执行一个操作(即System.out.println("hi");

我该怎么办


共 (2) 个答案

  1. # 1 楼答案

    ArrayList有一个名为contains()的方法,适用于此任务:

    Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

    您可以按如下方式使用它:

    if(!myList.contains(testNumber)) {
       PerformOperation();
    }
    
  2. # 2 楼答案

    你就是这么做的

    if (!myList.contains(testNumber))
        System.out.println("no element equals " + testNumber);
    

    严格来说,这可能不会将每个元素与testNumber进行比较。因此,如果你真的对比较每个元素的“手动”方式感兴趣,以下是方法:

    boolean found = false;
    for (int i : myList) {
        if (i == testNumber)
            found = true;
    }
    
    if (!found)
        System.out.println("no element equals " + testNumber);