什么是在 Kotlin 中连接两个字节数组的最简单方法?
考虑以下内容:
考虑以下内容:
val x = ByteArray(a);
val y = ByteArray(b);
请帮我将两个字节数组x,y
连接,并将结果存储到另一个ByteArray
中?
对于ByteArray
(和所有其他数组),有一个操作函数plus
operator fun ByteArray.plus(elements: ByteArray): ByteArray
Returns an array containing all elements of the original array and then all elements of the given elements array.
因此,您可以将此函数简单地用作运算符:
val z ByteArray = x + y
还有重载版本:
operator fun ByteArray.plus(element: Byte): ByteArray
operator fun ByteArray.plus(elements: Collection<Byte>): ByteArray
Iterable<T>
、Collection<T>
或Array<T>
)与另一个(Iterable<T>
、Collection<T>
、Array<T>
或Sequence<T>
)相加,然后获得一个List<T>
,Set<T>
和另一个(Array<out T>
、Iterable<T>
或Sequence<T>
)相加,然后获得Set<T>
。listA + arrayB
a + b
运算符将调用运算符函数 a.plus(b)
。fun main(args: Array<String>) {
val x = ByteArray(a);
val y = ByteArray(b);
val xLen = x.size
val yLen = y.size
val result = ByteArray(xLen + yLen)
System.arraycopy(x, 0, result, 0, xLen)
System.arraycopy(y, 0, result, xLen, yLen)
// so now result is array that concatenate two byte arrays x,y
}