【问题标题】:Returning true if all objects in an ArrayList share a common value如果 ArrayList 中的所有对象共享一个公共值,则返回 true
【发布时间】:2021-08-17 17:05:47
【问题描述】:

我有一个对象的 ArrayList,该对象是一个指令类,具有以下变量:toDelete、toUse、ID 和执行。为了让我的程序完成,只有当 ArrayList 的执行布尔值的所有成员都返回 true 时,我才需要返回 true。

public boolean getComplete() {
    for (int i = 0; i < instructionArea.size(); i++) {
        if (instructionArea.get(i).getExecuted() == false) {
            instructionsCompleted = false;
            return instructionsCompleted;
        } else
            instructionsCompleted = true;
    }
    System.out.println(instructionsCompleted);
    return instructionsCompleted;
}

这是我迄今为止的工作,但我知道这是错误的,程序没有正确执行。任何帮助将不胜感激,谢谢。

感谢您的回复,我实际上意识到我在其他地方的代码中有一些错误导致它无法正常工作。指令在它们应该被设置为“执行”之前。那好吧!谢谢大家

【问题讨论】:

  • 你能澄清一下“程序没有正确执行”的意思吗?具体来说,您看到的行为是什么?这与您希望/期望的行为有何不同?
  • 从理论上讲,该算法一目了然(即该方法将返回true iff。instructionArea 中所有对象的方法getExecuted() 是返回true 和@ 987654327@ 否则)。我支持@jhale1805 的minimal reproducible example 请求。

标签: java arraylist boolean


【解决方案1】:

假设变量instructionAreainstructionsCompleted 在别处定义并且对该函数可见,您的算法看起来不错。也就是说,这里有两个增强功能可以使代码更易于阅读(并因此更易于调试)。

请注意,我重组了函数以接收 BooleansArrayList 作为参数。在您的情况下,您可以将 Boolean 替换为 Instruction 对象,将 bool 替换为 instruction.getExecuted()

For-each 循环

由于您使用的是 ArrayList,it's a little more efficient 使用 for-each 循环而不是索引。考虑如下函数。

public boolean areAllTrue(ArrayList<Boolean> bools) {
    for (Boolean bool : bools) {
        if (!bool) return false;  // Return false if any element isn't true.
    }
    return true;
}

Java 的流式处理 API

您也可以使用Java's Streaming API 将此函数单行化。

public boolean areAllTrue(ArrayList<Boolean> bools) {
    return bools.stream().allMatch(bool -> bool == true);
}

【讨论】:

    【解决方案2】:

    或者你做一个反向来保存多行:) 它的流 API 风格像; "是any Match,还没有被执行)

    public boolean getComplete() {
        return !instructionArea.stream().anyMatch(i -> !i.getExecuted());
    }
    

    【讨论】:

      【解决方案3】:
      public boolean getComplete() {
          return instructionArea.stream().allMatch(InstructionArea::getExecuted);
      }
      

      如果所有元素都从getExecuted()返回true,则您的逻辑可能表示为返回true,而这段代码正是反映了这一点。

      它还使用了method reference(而不是 lambda),恕我直言,它使代码更优雅。

      【讨论】:

        【解决方案4】:

        让我们检查一下问题:
        一切都为真时,您希望返回真。

        您可以颠倒该要求:
        只有一个为假时返回假。

        按照这个逻辑,你可以做到以下几点:

        for (int i = 0; i < instructionArea.size(); i++) {
                if(!instructionArea.get(i).getExecuted()) {
                    return false; //when only one is false, it is not completed
                }
            }
        return true; // we iterated over all elements and all were executed, hence it is completed
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-17
          • 2019-06-13
          • 2014-02-03
          • 2020-01-31
          • 2020-05-05
          • 2014-06-19
          • 2016-02-27
          • 2022-01-23
          相关资源
          最近更新 更多