java - 如何改进检查两个字节数组是否相同的 Scala 代码?

标签 java scala compare

我有一个比较两个字节数组的方法。代码是java风格的,有很多“if-else”。

def assertArray(b1: Array[Byte], b2: Array[Byte]) {
  if (b1 == null && b2 == null) return;
  else if (b1 != null && b2 != null) {
    if (b1.length != b2.length) throw new AssertionError("b1.length != b2.length")
    else {
      for (i <- b1.indices) {
        if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
      }
    }
  } else {
    throw new AssertionError("b1 is null while b2 is not, vice versa")
  }
}

我试过如下,但并没有大大简化代码:

(Option(b1), Option(b2)) match {
    case (Some(b1), Some(b2)) => if ( b1.length == b2.length ) {
       for (i <- b1.indices) {
        if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
       }
    } else {
       throw new AssertionError("b1.length != b2.length")
    }
    case (None, None) => _
    case _ => throw new AssertionError("b1 is null while b2 is not, vice versa")
}

最佳答案

除非您将此作为学术练习,否则如何

java.util.Arrays.equals(b1, b2)

描述:

Returns true if the two specified arrays of bytes are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

我承认这是“Java 风格”:-)

因为你抛出了 AssertionErrors,你可以删除所有其他的:

def assertArray(b1: Array[Byte], b2: Array[Byte]): Unit = {
  if (b1 == b2) return;

  if (b1 == null || b2 == null) throw new AssertionError("b1 is null while b2 is not, vice versa")  

  if (b1.length != b2.length) throw new AssertionError("b1.length != b2.length")

  for (i <- b1.indices) {
    if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
  }
}

如果正如我怀疑的那样,您实际上是在 JUnit 测试中使用它(因此使用 assertArray),那么您可以使用我经常使用的技巧,比较数组的字符串表示:

def assertArray2(b1: Array[Byte], b2: Array[Byte]): Unit = {
  assertEquals(toString(b1), toString(b2))
}

def toString(b: Array[Byte]) = if (b == null) "null" else java.util.Arrays.asList(b:_*).toString

这将给你相同的结果(一个 AssertionError),不同之处在于。

关于java - 如何改进检查两个字节数组是否相同的 Scala 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7927404/

相关文章:

java - date_time 差异输出不正确

java - Clojure "eval"无法评估!

scala - 如何使用 Selenium WebDriverWait 获得更有意义的失败消息/断言?

scala - 如何覆盖 ScalaCheck 的一些生成器以强制(自动)生成精炼类型?仅非空列表,例如

scala - Akka-Stream 实现比单线程实现慢

java - 比较 hashMap 值

检查字符串 A 的数组是否包含字符串 B 的数组中存在的字母(不起作用)

java - 扫描仪导入显然有问题

java - 如何获取 Java 数组对象的大小 O(1)?

java - 是否可以将数组字符串与普通字符串进行比较?