是否存在Java技术来解决类中的重复循环?

我最近将此代码作为在线编码挑战的一部分提交,作为反馈的一部分,我被告知可以对部分代码进行改进以适应“良好实践”。我试图减少行数,但是没有任何提示,我仍然不确定如何改进。希望我能得到一些帮助。

public class ArrayChecker {
  public boolean check(int[] expected,int[] actual,int maxValue,int delta) {
    // Clip 'too large' values
    for (int i = 0; i < actual.length; ++i) {
      if (actual[i] > maxValue) {
        actual[i] = maxValue;
      }
    }

    // Check for length differences
    if (actual.length != expected.length) {
      return false;
    }

    // Check that each entry is within the expected +/- delta
    for (int i = 0; i < actual.length; ++i) {
      if (Math.abs(expected[i] - actual[i]) > delta) {
        return false;
      }
    }

    return true;
  }
}
oliver112233 回答:是否存在Java技术来解决类中的重复循环?

我首先要检查actualexpected的长度。然后,我将测试增量并在一个循环中一步一步执行裁剪(Math.min(int,int)会有所帮助)。喜欢,

public boolean check(int[] expected,int[] actual,int maxValue,int delta) {
    if (actual.length != expected.length) {
        return false;
    }
    for (int i = 0; i < actual.length; ++i) {
        if (Math.abs(expected[i] - Math.min(maxValue,actual[i])) > delta) {
            return false;
        }
    }
    return true;
}

如果使用Java 8+,则可以将其减少为lambda。

public boolean check(int[] expected,int delta) {
    if (actual.length != expected.length) {
        return false;
    }
    return IntStream.range(0,actual.length)
            .noneMatch(i -> Math.abs(expected[i] - Math.min(maxValue,actual[i])) > delta);
 }

最后,返回(复杂)一行,就像

public boolean check(int[] expected,int delta) {
    return actual.length == expected.length && IntStream.range(0,actual[i])) > delta);
}
本文链接:https://www.f2er.com/3148985.html

大家都在问