将子数组复制到初始化数组中的 Java 方法
Posted
技术标签:
【中文标题】将子数组复制到初始化数组中的 Java 方法【英文标题】:The Java way to copy a subarray into an initialized array 【发布时间】:2017-02-27 07:07:48 【问题描述】:outputArray[w:lastIndex] = array[v:lastIndex]
我想将一个子数组复制到另一个已经初始化的子数组中。
有没有可以检查的内置函数:
1) 要复制的元素数量相同。 2) 它不会导致 indexOutOfBoundException
在 RHS 上,我可以执行以下操作:
Arrays.copyOfRange(array,v,lastIndex+1)
我不知道在 LHS 上是否可以做任何事情。
我必须使用整数数组 + 我知道它违背了数组的用途。
【问题讨论】:
【参考方案1】:你可以使用System.arraycopy
:
System.arraycopy (sourceArray, sourceFirstIndex, outputArray, outputFirstIndex, numberOfElementsToCopy);
但是,如果您提供了无效参数,则会抛出 IndexOutOfBoundsException
。
如果我正确理解您示例中的参数,您需要类似:
System.arraycopy (array, v, outputArray, w, lastIndex - v);
或
System.arraycopy (array, v, outputArray, w, lastIndex - v + 1);
如果你也想复制lastIndex
处的元素。
【讨论】:
【参考方案2】:您可以使用System#arraycopy
,它接受源数组和目标数组中起始索引的参数:
System.arraycopy(array, v, outputArray, w, lastIndex - v)
【讨论】:
【参考方案3】:也许你可以使用fill函数。
【讨论】:
我根本不知道填充功能。谢谢。很高兴知道。【参考方案4】:你可以使用 ArrayUtils 库的 addAll 方法
来自文档https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html
Adds all the elements of the given arrays into a new array.
The new array contains all of the element of array1 followed by all of the elements array2. When an array is returned, it is always a new array.
ArrayUtils.addAll(null, null) = null
ArrayUtils.addAll(array1, null) = cloned copy of array1
ArrayUtils.addAll(null, array2) = cloned copy of array2
ArrayUtils.addAll([], []) = []
ArrayUtils.addAll([null], [null]) = [null, null]
ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
Parameters:
array1 - the first array whose elements are added to the new array, may be null
array2 - the second array whose elements are added to the new array, may be null
Returns:
The new array, null if both arrays are null. The type of the new array is the type of the first array, unless the first array is null, in which case the type is the same as the second array.
Throws:
IllegalArgumentException - if the array types are incompatible
[1]: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html
【讨论】:
它确实非常优雅地处理空元素。但我猜 apache commons 会是开销。以上是关于将子数组复制到初始化数组中的 Java 方法的主要内容,如果未能解决你的问题,请参考以下文章
一些典型的数组处理方法 赋值初始化 寻找最大值 计算平均值 复制数组 颠倒数组中元素的顺序 矩阵相乘 数组的输出
请问java中深度copy一个二维数组是啥意思?怎么用代码实现?