gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:14:13 25 4
gpt4 key购买 nike

我有一个比较两个字节数组的方法。代码是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com